Time for JavaScript Async / Await
JavaScript Async / Await
Promises are one of the finest additions to JavaScript because they make it so much easier to work with async code. Going from callbacks to promises feels like a significant improvement, but there is something even better than promises: async/await. Async/await is an alternate solution syntax for promises that makes reading/writing async code easier, but there are a few caveats you should be aware of before using it, or you risk making your code worse.
To understand async/await, it is best, to begin with an example
of promises and then convert that to async/await. To begin, we will use the
function below in all of our examples.
function setTimeoutPromise(delay) {
return new Promise((resolve, reject) => {
if (delay < 0) return reject("Delay must be greater than 0")
setTimeout(() => {
resolve(`You waited ${delay} milliseconds`)
}, delay)
})
}
This function is nothing more than a promise-based version
of setTimeout. Now consider how we would chain two timeouts together, with the
second timeout waiting for the first to complete.
setTimeoutPromise(250).then(msg => {
console.log(msg)
console.log("First Timeout")
return setTimeoutPromise(500)
}).then(msg => {
console.log(msg)
console.log("Second Timeout")
})
// Output:
// You waited 250 milliseconds
// First Timeout
// You waited 500 milliseconds
// Second Timeout
If you're familiar with promises, this code shouldn't be too
difficult to understand. The most perplexing part of the code is that we return
the second promise from the first so that we can chain them together. This code
currently works, but we can make it much cleaner by using async/await.
doStuff()
async function doStuff() {
const msg1 = await setTimeoutPromise(250)
console.log(msg1)
console.log("First Timeout")
const msg2 = await setTimeoutPromise(500)
console.log(msg2)
console.log("Second Timeout")
}
// Output:
// You waited 250 milliseconds
// First Timeout
// You waited 500 milliseconds
// Second Timeout
The above code accomplishes the same task as the previous
version, but it appears much more like normal synchronous code, which is the
point of async/await. Let's take a look at how this code works.
To begin, you'll notice that we encapsulated all of our code
in a function called doStuff. This function's name is unimportant, but you'll
notice that we labeled it as async by placing the async keyword before the
function keyword. This informs JavaScript that we intend to use the await
keyword in this function. If we do not label the function as async and do not
use the await keyword within the function, an error will be thrown.
It's also worth noting that you can't use the await keyword
unless you're inside a function right now, which is why we had to write one to
run this code. This is something that JavaScript intends to change by adding
top-level await, which means that you can use await at the top level of a file
without being in a function, but it is still not supported by any browsers.
Let's talk about the code in the function now that we've
covered the async keyword. It appears to be very similar to the previous code
because async/await is simply a different way of writing the same thing. To
convert a promise. then to async/await, use the promise function call
setTimeoutPromise(250) followed by the keyword await. This indicates to
JavaScript that the function following the await keyword is asynchronous. Then,
if your promise returns a value, you can simply access it as if it were a
regular function return, as we did with const msg1 = await setTimeoutPromise
(250). The final step is to paste all of the code from the promises. then
section after the function call.
This works because when JavaScript encounters the await
keyword, it will invoke the awaited function but will not execute any code
following that function until the promise returned by that function is
resolved. Instead, while waiting for the promise to resolve, JavaScript will
execute code elsewhere in your application. When the promise is resolved, it returns
the promised result from the awaited function and runs all the code until the
next await statement, then repeats.
Conclusion
While async/await does not allow you to do anything new in
JavaScript, it is extremely useful because it can make your code much cleaner.

Comments
Post a Comment