Introduction to Promises and Async and Await Promises in Javascript!✨
What is a Promise?
A promise is an object that may provide a value sometime in the future: either a resolved value or a reason that it’s not resolved (e.g., an error occurred). A promise may be in one of 3 possible states: fulfilled, rejected, or pending.
How do Promises work?
A JavaScript Promise object can be:
Pending
Fulfilled
Rejected
The Promise object supports two features: state and result
.
While a Promise object is " pending " (working), the result is undefined.
When a Promise object is " fulfilled ", the result is a value.
When a Promise object is " rejected ", the result is an error object.
Now let's take a real-world example to understand promises more precisely.
Suppose, you visit a Coffee Shop and place an order for a coffee. Then, the staff says that he has to check whether the Black Coffee is available or not. (So in this case, it returns a promise.)
If your Black Coffee is available, then the staff will accept your order. (In this case, the promise will be fulfilled. So, it will be resolved.)
And suppose, you place an order for black tea, and if the tea is not available, since it's a coffee shop, then the staff won't accomplish your order. (In this case, the promise is unfulfilled and as a result, it is rejected.)
After placing your order for the Black Coffee, it will take some time to process. After processing your request, you will receive your black coffee, and you will leave the shop happily!
Now let's code this for a better understanding!
Promise Chaining
Promise.then()
always returns a new promise, it’s possible to chain promises with precise control over how and where errors are handled.
For example:
function placeOrder(drink){
return new Promise(function(resolve,reject){
if(drink==='blackCoffee'){
resolve("Order Placed. YAYYYYYY!!!")
}
else{
reject("Sorry,We only serve coffee. :(")
}
})
}
function processOrder(order){
//once accepted, your order can't be rejected.So only resolve will work here
return new Promise(function(resolve){
console.log("Order is being processed");
resolve(`Black Coffee is served for the ${order}`);
})
}
// Scenario with Promises
placeOrder('blackCoffee').then(function(orderFromCustomer){
console.log("Request received");
let orderProcessed=processOrder(orderFromCustomer);
return orderProcessed;
}).then(function(orderProcessed){
console.log(orderProcessed);
}).catch(function(err){
console.log(err);
})
// Output:
// Request received
// Order is being processed
// Black Coffee is served for the Order Placed. YAYYYYYY!!!
For error handling, we use Promise.catch()
. If you chain promises, the .catch()
method will catch errors that occur in any promise. If an error occurs and you don’t have the .catch()
method, the JavaScript engine issues a runtime error and stops the program.
For example:
function placeOrder(drink){
return new Promise(function(resolve,reject){
if(drink==='blackCoffee'){
resolve("Order Placed. YAYYYYYY!!!")
}
else{
reject("Sorry,We only serve coffee. :(")
}
})
}
function processOrder(order){
//once accepted, your order can't be rejected.So only resolve will work here
return new Promise(function(resolve){
console.log("Order is being processed");
resolve(`Black Coffee is served for the ${order}`);
})
}
// Scenario with Promises
placeOrder('blackTea').then(function(orderFromCustomer){
console.log("Request received");
let orderProcessed=processOrder(orderFromCustomer);
return orderProcessed;
}).then(function(orderProcessed){
console.log(orderProcessed);
}).catch(function(err){
console.log(err);
})
// Output:
// Sorry,We only serve coffee. :(
Now suppose, we have a bigger scenario where we have multiple process requests. So solving those with the help of Promise Chaining would be a tiresome job. So we have an extended version of Promises, which is known as async-await,
which is a clean version of Promises. It’s undoubtedly easy to understand and use.
Promise Async and Await
Async
Functions will always return a value. It makes sure that a promise is returned and if it is not returned, then JavaScript automatically wraps it in a promise, which is resolved with its value. Await
function is used to wait for the promise. It could be used within the async block only. It makes the code halt until the promise returns an output. It only makes the async block wait.
For error handling in async-await,
we use the try...catch
block.
The code that we want to execute, we put within a
try
block and when performing that execution, if an error comes, we put that into a.catch()
block.When returning a promise within a
try
block, make sure toawait
it, if you want thetry...catch
block to catch the error.
function placeOrder(drink){
return new Promise(function(resolve,reject){
if(drink==='blackCoffee'){
resolve("Order Placed. YAYYYYYY!!!")
}
else{
reject("Sorry,We only serve coffee. :(")
}
})
}
function processOrder(order){
return new Promise(function(resolve){
console.log("Order is being processed");
resolve(`Black Coffee is served for the ${order}`);
})
}
//Async-await
async function serveOrder(){
try{
const orderReceived=await placeOrder('blackCoffee');
console.log(orderReceived);
const processedOrder=await processOrder(orderReceived);
console.log(processedOrder);
}
catch(error){
console.log(error);
}
}
serveOrder();
//Output:
// Order Placed. YAYYYYYY!!!
// Order is being processed
// Black Coffee is served for the Order Placed. YAYYYYYY!!!
function placeOrder(drink){
return new Promise(function(resolve,reject){
if(drink==='blackCoffee'){
resolve("Order Placed. YAYYYYYY!!!")
}
else{
reject("Sorry,We only serve coffee. :(")
}
})
}
function processOrder(order){
return new Promise(function(resolve){
console.log("Order is being processed");
resolve(`Black Coffee is served for the ${order}`);
})
}
//Async-await
async function serveOrder(){
try{
const orderReceived=await placeOrder('blackTea');
console.log(orderReceived);
const processedOrder=await processOrder(orderReceived);
console.log(processedOrder);
}
catch(error){
console.log(error);
}
}
serveOrder();
//Output:
// Sorry,We only serve coffee. :(
That's it, Thanks for making it to the end, hope you learned something interesting. Let's connect on Twitter, GitHub and LinkedIn
Have a great day! :)