Callbacks and promises are great when it comes to performing async operations. Promises improved over callbacks and provide a flat code syntax, especially when it comes to chaining promises. The operators on promises like allSettled
, any
, then
and catch
make it easier to write complex async operations.
Async/Await was introduced in ES7 to promote a cleaner syntax to promises. Under the hood, async/await are promises; they provide a nice abstraction layer under those keywords.
Async
async
keyword could be used in front of any function (declaration, expressions, callbacks or literally anywhere). All it means is that the function will always return a promise. Any return values other than a promise will be wrapped in a resolved promise.
async function foo() {
return "Parwinder" // returning a string but `async` will ensure it is wrapped in a promise
}
foo().then((data) => { // we can safely use then because async function foo returns a promise
console.log(data); // Parwinder
})
We could return a promise in function foo
, and it will still work. It will be unnecessary, though.
async function foo() {
return Promise.resolve("Parwinder")
}
foo().then((data) => {
console.log(data); // Parwinder
})
Await
await
keyword makes JavaScript wait until the promise settles and returns its result. It can only be used inside an async
function.
async function foo() {
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Parwinder"); // resolves with "Parwinder" after 2 seconds
}, 2000);
});
// will not move to the next line until myPromise resolves/rejects
const name = await myPromise;
// the execution pauses (or awaits) for the promise
console.log(name); // Parwinder
}
foo();
As you can see in the above example await
provides a cleaner syntax compared to Promise.then
.
Top comments (6)
It's important to note that await can also be used on non-promises, in which case it passes the value through.
This means that await can be used to resolve things that may or may not be promises.
Yep! My async/await blog post is a 3 part series. The 3rd part discusses this. You just have to await ๐
Great explanation !!!
Short and clear I like this kind of blogs ๐๐
You are killing it with this series! Loving the posts ๐
You are far too kind. I appreciate the feedback โฅ๏ธ
Async
keyword also mean the functions used inside are asynchronous ^^