Open In App

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

Last Updated : 23 May, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Example:

Javascript




<script>
    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);
            console.log(response);
        } catch (err) {
            console.log(err);
        }
    }
  
    // Makes connection request to GFG
    doStuff('GFG');
  
    // Makes connection request to Google
    doStuff('Google');
</script>


Output:

Connected  :)
Connection failed  :(

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads