Promises its super cool π
Questions π€
- What is callback? how do you pass an argument to a callback?
- How do you save time with the promise
- Callback vs Promise vs Async/Await
- What is the Promise APIs?
- How does Promise work behind the scene?
- What is Microtasks? How does it work?
The Callback
A callback is a simple function which is then passed into an asynchronous function as an argument to perform on a certain event in the future and the return value of callback function will be parameters of called function
Nested Callback
Consider you want to manufacture a bicycle that involves multiple stages to get one bicycle ready on very high designBiCycle, constructFrame, paintFrame, assembleParts, testingBicycle, releaseBicycle, and many other how do we do it asynchronously Because each function output will be about for another function!. How to chain them now π€
Well it's possible with a callback method chaining to let's see how it looks in code
Finally, we achieved what we were looking for but isn't it messy. If we have some huge scenario then will end up in CALLBACK HELL
where code becomes unreadable and non-maintainable. To get rid of this ES6 introduced promise
to rescue us
What will be the output of following code block
Why? if you see the log that printed via our code seems to incorrect isn't it! Actually, the answer is NO the output of the following code is accurate.
Even though we declare setTimeout before the callback, setTimeout will take its own time to execute and callback takes its own. Both setTimeout and callback jobs will be enqueued into the Task Queue
and Microtasks Queue
accordingly. Since a job in Microtasks Queue will have a high priority callback
will execute before setTimeout.
Promise it's crazy
Let's see Promise
with real-life analogies.
Conversation of Niece π§π» and Uncle ππ»ββοΈ
Niece:Hey, uncle, On my 5th B'Day, can you gift me a bicycle with Barbies stickers on it? π₯Ί
Me:Yes Baby anything for you π (Made a promise)
Niece:I'll call all my friends to show my new π². Let me know when you're going to bring it uncle π (promise return value)
Me:Sure, but what if i don't find a bicycle with Barbies stickers on it? π€·π»ββοΈ
Niece:In that case you let me know immediately (failure Callback). In case if you find what I was looking for then bring it on (success callback)
The analogy isnβt terribly accurate, because JavaScript promises are more complex than a simple subscription list: they have additional features and limitations. But itβs fine, to begin with.
The promise in javascript is something that takes time to get the things done by which it doesn't like to hold others' work. Promise will work independently. all the jobs of the Promise will be enqueued into the Microtasks queue and then it will be dequeued when the task is completed
Promise Constructor
A Promise Constructor hold two properties that is PromiseStatus
[[PromiseStatus]] and PromiseValue
[[PromiseValue]]
πΈ PromiseStatus represent a status of promise that will be fulfilled/resolved
, pending
, or rejected
πΈ PromiseValue represent a value of the promise that is being resolved
or rejected
The basic syntax of the promise looks something like this
The function passed to the new Promise is called the executor. Which run and produce some results eventually.
Its arguments resolve
and reject
are callbacks provided by JavaScript itself. When the executor obtains the result, be it soon or late, doesnβt matter, it should call one of these callbacks.
πΈ resolve(value)
β if the job finished successfully, with result value.
πΈ reject(error)
β if an error occurred, error is the error object.
In the above example, myPromise
is an object obtained by Promise constructor. Which will have both status and result.
- Initially status of the promise will be
pending
and changes to eitherresolved
orrejected
- Initially the value of the result will be
undefined
and eventually it will change to resolved value or rejected error
Things to remember
- There can be only a single result or an error. Which means executor can call
resolve
orreject
method only once. All further calls ofresolve
andreject
will be ignored
- resolve and reject method accept only one argument or none arguments
- If something goes wrong with executor will be notified with reject which accepts any type but the recommendation is to use
Error Object
- The properties of promise that is
status
andresult
will be internal. We can't directly access them directly in order to get the value of those properties we should usethen
,catch
, orfinally
TBU
- Add diagram of Promise constructor properties
- Add illustration of how a promise works
Chaining Promise
In the above callback section, we try to demonstrate a bicycle manufacturing process and we finally came up with a callback solution that is messy and looks very ugly. To solve that problem ES6 also provided a way to chain them using promise chining
then()
isn't the end of the story, we can chain thens together to transform values or run additional async actions one after another
Let's try to achieve the above solution using Promise chaining
Look now how beautifully π we can write code and achieve same requirement using Promise Chaining this is Promise Heaven
π
TBU
Add promise chining illustration
Promise APIs
Promise class contains 5 methods those are
πΈPromise.all
If we want to execute a number of promise parallelly then we can go ahead with promise.all
which accepts an array of promise and process the contents once all are done
In c# we have
Task.WhenAll()
similar toPromise.all
Remember
If one promises rejects, Promise.all immediately reject,completely forgetting about the other ones in the list. Their results are ignored.
πΈPromise.allSettled
Since Promise.all
reject a promise if one fails this is good only for all/none
case Whereas Promise.allSettled
methods execute parallelly but even if one method fail it won't boughter it will execute the remaining method until all are completed. So that each promise will have value/error in the response
πΈPromise.race
Similar to Promise.all
, but waits only for the first settled promise and gets its result (or error). If anyone promise process fast that became the result and remaining promise will be ignored
In c# we have
Task.WhenAny()
similar toPromise.race
πΈPromise.resolve
Makes a resolved promise with the given value
πΈPromise.reject
Makes a rejected promise with the given error.
TBU
Add illustration for promise APIs
For more visualized demonstration read the blog written by Lydia Hallie
Reference