What is Javascript Promise and how can create a new Promise and Handle It?
A JavaScript promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Promises are a way to handle asynchronous code in JavaScript, and they were introduced in ECMAScript 6 (ES6) as an alternative to callback functions.
Here's an example of creating a promise:
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() < 0.5) {
resolve('Hello, World!');
} else {
reject(new Error('Something went wrong!'));
}
}, 2000);
});
In this example, we create a promise by passing a function called the "executor" to the Promise
constructor. The executor function takes two arguments: resolve
and reject
. These functions are used to signal the completion or failure of the asynchronous operation. In this example, we use setTimeout
to simulate an asynchronous operation that takes 2 seconds to complete. At the end of the 2 seconds, we use Math.random()
to randomly decide whether to call resolve
or reject
.
Once a promise has been created, we can attach callbacks to it using the .then()
and .catch()
methods. Here's an example of how we can handle the promise:
myPromise
.then(result => console.log(result))
.catch(error => console.error(error));
In this example, we call .then()
to attach a callback that will be called if the promise is resolved. The result
passed to the then
callback is the result of the operation passed to resolve
. We also call .catch()
to attach a callback that will be called if the promise is rejected. The error
passed catch
callback is the error passed to reject
.
We can chain multiple then
methods, and the result of the first then
will be passed as a parameter to the next one.
myPromise
.then(result => {
return result + "!";
})
.then(result => {
console.log(result);
})
Promises are very useful in JavaScript as they help us write more readable, maintainable, and powerful code by handling asynchronous operations.
It's worth noting that Promises is just one way to handle asynchronous code, other way like async-await, callback functions are also common but with ES2017 async-await became more common and easier to read and understand.
async-await
allows you to write asynchronous code that looks and behaves like synchronous code. Here's an example of how you can use async-await
with a promise:
async function myAsyncFunction() {
try {
const result = await myPromise;
console.log(result);
} catch (error) {
console.error(error);
}
}
In this example, myAsyncFunction
is declared as async
, which means it returns a promise. Inside the function, we use the await
keyword to wait for the promise to resolve before continuing. The resolved value of the promise is then stored in the result
variable. If the promise is rejected, the error is caught in the catch
block.
It's worth noting that await
can only be used inside an async
function.
The async-await
syntax makes asynchronous code look and behave like synchronous code, which makes it more readable, maintainable and also easy to understand. This makes the code more predictable and easy to reason about, which can make it easier to write and debug.
Keep in mind that async-await
is built on top of promises, so it still works with a promise. And also you still can use promises while using async-await.