Async and Await: Making Promises Easier Since 2017
The async and await features were introduced in Javascript as part of ECMAScript 2017.
Async and await provide a simple and intuitive syntax for interacting with promises. Among the many perks of using async/await for your asynchronous code are their improved error handling, less nutty nesting with conditionals and .then()s, and that they are easier to use with debuggers.
Async
The async keyword can be used to turn any function into an async function.
Async functions always return a promise.
Just place the async keyword at the beginning of any function expression or declaration. Take a look at the async function syntax examples from MDN below:
function tearingUp() {
return "It's tearin' up my heart when I'm with you. But when we are apart, I feel it too"
}
async function myHeart() {
return "And no matter what I do, I feel the pain. With or without you"
}
console.log(tearingUp()) // "It's tearin' up my heart when I'm with you. But when we are apart, I feel it too"
console.log(myHeart()) // Promise { <state>: "fulfilled", <value>: "And no matter what I do, I feel the pain. With or without you" }
You can interact with the returned promise from an async function using the .then() method, but there's another way: await.
Await
The await keyword can only be used inside async functions. Await literally waits for the promise to resolve before continuing on the current line of code.
async function digitalDigital() {
let firstPart = Promise.resolve(`Digital, digital get down`)
let nextPart = await firstPart + ` (get down) just you and me`
console.log(nextPart) // "Digital, digital get down (get down) just you and me"
}
Note - if you await a lot of promises all in a row you may slow down your run time significantly
In Conclusion...
Async and await make reading and writing asynchronous code much easier. You can save space by decluttering all your old .then()s, turn any function into a promise, and halt your code while waiting for a promise to resolve.
async function byeByeBye() {
let amazingLyric = new Promise((resolve, reject) => {
setTimeout(() => resolve("Baby bye bye bye"), 2000)
});
let dunzo = await amazingLyric;
alert(dunzo)
}
byeByeBye() // "Baby bye bye bye"
Here are some of the handy resources I used in researching this post:
Top comments (0)