Skip to content
Related Articles
Open in App
Not now

Related Articles

How to use Async-Await pattern in example in Node.js ?

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 23 May, 2022
Improve Article
Save Article

Modern javascript brings with it the async-await feature which enables developers to write asynchronous code in a way that looks and feels synchronous. This helps to remove many of the problems with nesting that promises have, and as a bonus can make asynchronous code much easier to read and write.

To use async-await, we just need to create an async function in which we will implement our try-catch block. In the try block, we will await our promise to be completed. If it gets resolved we will get the result otherwise an error will be thrown through the catch block. Await can only be used inside an async function or async callback or async arrow function.



    function makeConnection(request) {
        // Promise resolves if connection is
        // made to GFG else it is rejected
        return new Promise((resolve, reject) => {
            if (request == 'GFG')
                resolve('Connected  :)');
            else reject('Connection failed  :(');
    async function doStuff(request) {
        try {
            const response = await makeConnection(request);
        } catch (err) {
    // Makes connection request to GFG
    // Makes connection request to Google


Connected  :)
Connection failed  :(
My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!