What async function doing?
Async/await can be tricky to understand. It can seem like you sprinkle in `async` or `await` randomly to make things work.
Let’s take a look at what they mean to get a sense for when you need them.
Consider
async function doIt() {
return 'hi';
}
This is essentially the same as returning a promise that’s resolved with ‘hi’.
function doIt() {
return new Promise((resolve) => {
resolve('hi');
});
}
In other words, making a function “async” means it will always returns a promise.
What about ‘await’
const thing = await doIt();
console.log(thing);
Remember that `doIt` is async and returns a promise. Await-ing it is (basically) the same as calling the promise’s `then` and then continuing on.
doIt().then((thing) => {
console.log(thing);
});
Okay, how about multiple awaits?
const thing1 = await doIt1();
const thing2 = await doIt2();
console.log(thing1, thing2);
In this case, it’s equivalent to chain of `then` calls.
doIt1().then((thing1) => {
return doIt2().then((thing2) => {
console.log(thing1, thing2);
});
});
By using async/await, we avoid an ever-expanding chain of nested callback hell.
The important thing to keep in mind is you’re dealing with promises. So if you’re returning a promise…
async function fetchThing() {
// Assuming fetch returns a promise...
return await fetch(url);
}
…you don’t need async/await. Just return the promise
function fetchThing() {
// ...return the promise directly
return fetch(url);
}
which has the same end result.