Firstly - they're the same 😀
They (async awaits) are the mystery that makes every asynchronous file look pretty. They bring joy to the eyes of anyone who one saw the same joy when moving away from callback hell.
You guessed it, this is yet another blog about async await vs promises. But don’t worry i’ll keep it very short and hopefully this is the last one you'll need to read.
If you’re hear because you’re a little confused as to what happens or how Async Await works so magically — this abstracted explanation can shed a little better light.
Firstly lets create a promise:
const getData = new Promise((resolve, reject) => {
// crazy calculation that takes 10 seconds and spits out the //number 55
const data = 55;
if (data) {
resolve (55);
} else {
reject ("Error state");
}
})
Suppose we want to call this function — the way we’d interface with it is to work with the resolve callbacks output.
Maybe there’s a button, that, when clicked on calls a fetchInfo
function — if we were to then resolve our code with promises using the then
property, we’d end up landing with:
const fetchInfo = getData().then((data) => {
return fetchFromDB(id).then((dbData) => {
return `This is the dbData: ${dbData}`
})
})
Now that doesn’t look too bad… but it can look better with Async Await — have a see yourself. The Async Await equivalent of the above
const fetchInfo = async () => {
const id = await getData();
const dbData = await fetchFromDB(id);
return `This is the dbData: ${dbData}`
}
I guess thats it — plain and simple a side by side comparison.
The core of Async-Await a pattern adapted from C#, is to linearise code readability, because sometimes getting lost in thens
can make it difficult to follow code paths.
By wrapping a function in async, JS reads it to be a promise and the await within the function acts as the equivalent
of then, to resolve the getData
promise
Follow me on LinkedIn || Twitter, heaps more articles to come
If you've got a topic you'd like me to write on - tweet me 😀
Also, I'd always love feedback on this in the comments 👇 if this helped you - support the article by hitting that ❤️
Top comments (0)