Inquisitive, student, teacher and a wanna be story teller. Working on https://learningpaths.io/
I recently read a medium post where the author claimed that using
async-await is better than using
promises. While this might hold good in general cases, I think that generalisation was too broad and doesn’t do justice to either
I read somewhere that
async-await is syntactical sugar for using
promises. So before getting to know
catchfor all practical purposes.
.thenmethods for all the promises.
Promiseobject whether they are static methods or prototype methods is again a
Promise.allthe order of the promises are maintained in values variable irrespective of which promise was first resolved.
Once you have wrapped your head around promises checkout
Here are a list of thumb rules I use to keep my head sane around using
asyncfunctions returns a promise.
asyncfunctions use an implicit Promise to return its result. Even if you don’t return a promise explicitly
asyncfunction makes sure that your code is passed through a promise.
awaitblocks the code execution within the
asyncfunction, of which it(
await statement) is a part.
awaitstatements within a single
async awaitmake sure to use
try catchfor error handling.
awaitwithin loops and iterators. You might fall into the trap of writing sequentially executing code when it could have been easily done in parallel.
awaitis always for a single promise.
awaitonly blocks the code execution within the
asyncfunction. It only makes sure that next line is executed when the
promiseresolves. So if an asynchronous activity has already started then
awaitwill not have an effect on it.
The answer is that we will use both. Following are the thumb rules I use to decide when to use
promises and when to use
async functionreturns a
promise.The converse is also true. Every function that returns a
promisecan be considered as
awaitis used for calling an
async functionand wait for it to
awaitblocks the execution of the code within the
asyncfunction in which it is located.
function2is dependent on output of
function1then I use
async functionsand then run them in parallel.
awaitremember that you are writing blocking code. Over the time we tend to neglect this.
async functionswith many
await asyncFunction()in it, it is better to create smaller
async functions.This way we will be aware of not writing too much of blocking code.
async functionsis that you force yourself to think what are the async functions that can be run in parallel.
asyncfunction. By doing this you are making sure that somebody else can use your function asynchronously.
Hope this helps you decide easily when to use promises and when to use
promises and when to use
If you liked this article and would like to read similar articles, don’t forget to clap.
This article is a part of my learning series, which I call Understanding X. You can read more above it in this link.