Introduction to Promises and Async and Await Promises in Javascript!✨

Introduction to Promises and Async and Await Promises in Javascript!✨

Featured on daily.dev

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 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 you place an order for a Black 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 accepts your order. (In this case, the promise will be fulfilled. So, it will be resolved.)

And suppose, you place an order for the Black Tea and if tea is not available, since its a Coffee shop, then the staff wouldn't accomplish your order. (In this case, the promise is unfulfilled and as a reason, it is rejected.)

After placing your order for the Black Coffee, it will take some time to process. And after processing your request, you will receive your Black Coffee and you 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 occurred 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 which we want to execute, we put that 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 to await it, if you want the try...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 or LinkedIn

Have a great day! :)