Today I wanted to talk about async/await in JavaScript. They are syntactic sugar in JavaScript that help organize and keep our asynchronous code concise. Before this addition to the language, the usual way of dealing with asynchronous code was by using a .then
chain.
.then
is a method that runs a callback you pass to it when the Promise
has finished. Here is an example of how you would traditionally use promises and .then
.
function multiplyBy2(x) {
return new Promise(resolve => {
setTimeout(() => {
resolve(x * 2);
}, 2000);
});
}
function addPromises(x){
return new Promise(resolve => {
multiplyBy2(10)
.then((a) => {
multiplyBy2(20)
.then((b) => {
multiplyBy2(30)
.then((c) => {
resolve(x + a + b + c);
})
})
})
})
}
addPromises(10).then(sum => console.log(sum))
As you can see we are waiting two seconds after each multiplyBy2() function is called. There is nothing inherently wrong with that since this is a contrived example, but the problem lies in how it looks and is structured. Using all of the nested
.then
methods is extremely hard to read and decreases maintainability in our code. For a real world example we might need to asynchronously get data from an API and have tasks to do after we receive the data like using the .json() method on it.
Enter Async/Await
We'll need to create a new function that I'm naming addAsync
. It will have the same purpose as addPromises
but will be much more maintainable. This function is different because we will append the keyword async
before declaring the function. Putting async
before your function means that it will always return a Promise
async function addAsync(x) {
// code here...
}
Now we need to put the await
keyword in that function so that it has the same functionality as addPromises
async function addAsync(x) {
const a = await multiplyBy2(10);
const b = await multiplyBy2(20);
const c = await multiplyBy2(30);
return x + a + b + c;
}
addAsync(10).then(sum => console.log(sum))
Now doesn't that look more manageable?!?! Let's go through what this code is actually doing. As I said above, async
always returns a Promise. await
makes JavaScript wait until the Promise
from multiplyBy2()
on each line resolves and then returns its result. This enables us to do a whole array of things with our data and not have to worry about when the asynchronous request is going to come back. JavaScript simply runs the code line by line.