How to use Async & Await with promises in node.js

Punitkumar Harsur
3 min readJun 17, 2020

--

Async function:

An async function is a modification to the syntax used in writing promises. You can call it syntactic sugar over promises. It only makes writing promises easier.

An async function returns a promise — if the function returns a value, the promise will be resolved with the value, but if the async function throws an error, the promise is rejected with that value. Let’s see an async function:

async function myRide() {
return '2017 Dodge Charger';
}

and a different function that does the same thing but in promise format:

function yourRide() {
return Promise.resolve('2017 Dodge Charger');
}

From the above statements, myRide() and yourRide() are equal and will both resolve to 2017 Dodge Charger. Also when a promise is rejected, an async function is represented like this:

function foo() {
return Promise.reject(25)
}
// is equal to
async function() {
throw 25;
}
Async-function using Promise

The function execution “pauses” at the line (*) and resumes when the promise settles, with result becoming its result. So the code above shows “done!” in one second.

Let’s emphasize: await literally makes JavaScript wait until the promise settles, and then go on with the result. That doesn’t cost any CPU resources, because the engine can do other jobs in the meantime: execute other scripts, handle events, etc.

It’s just a more elegant syntax of getting the promise result than promise.then, easier to read and write.

Await

Await is only used with an async function. The await keyword is used in an async function to ensure that all promises returned in the async function are synchronized, ie. they wait for each other. Await eliminates the use of callbacks in .then() and .catch(). In using async and await, async is prepended when returning a promise, await is prepended when calling a promise. try and catch are also used to get the rejection value of an async function. Let's see this with our date example:

async function myDate() {
try {
let dateDetails = await date;
let message = await orderUber(dateDetails);
console.log(message);
} catch(error) {
console.log(error.message);
}
}

Lastly we call our async function:

(async () => { 
await myDate();
})();

Note we used the ES6 arrow function syntax here.

Async with promise
Async-Await chaining

Conclusion

Understanding the concepts of Callbacks, Promises, and Async/Await can be rather confusing, but so far we have seen how they work when carrying out asynchronous operations in JavaScript.

--

--

Punitkumar Harsur

Data science SME. Hustler, Content creator, Photography Enthusiast. LinkedIn: www.linkedin.com/in/punityh