Before learning about promise it’s important to know what Asynchronous programming .
In asynchronous programming, the program continues to execute tasks without waiting for other program to complete any task. It is independent and it uses callbacks, ==promises== to wait for the tasks. This technique allows the program to run concurrently and use resources efficiently.
"I Promise a Result!"
"Producing code" is code that can take some time
"Consuming code" is code that must wait for the result
A Promise is an Object that links Producing code and Consuming code
() => x
is short for
() => { return x; }
.
A simple example code in Javascript
We are using fetch API to get the data from the endpoint and then chaining the result.
How it works
- First the fetch return a promise that resolves to Response object if success or Reject if failed.
- Our first
.thenblock processes the resolved Response object.Here either error or the promise is thrown. - Our second
.thenblock processes the parsed JSON data. - Our last chain catches error if there’s any.
|
|
Our above example is a good example of using promise but there is a small bug where the data is not stored correctly in the jsonData variable.
Why the heck is the data not being stored in our variable?
This is because the whole point of promise is to let other synchronous code run and not block the rest of the program to execute. It is a feature and not a bug.
Let’s understand this
when the fetch() function is called , it is supposed to return a new Promise object, which takes times as it has to connect to the network and get the data right? So, our code doesn’t get blocked, it instead leaves all the things inside the fetch() function like other .then() and .catch() to run later after the fetch() resolves the result and directly moves to execute other part of the code, which in our case is console.log("jsonData: "+jsonData); since nothing has been returned by the promise yet the output results to undefined
How to fix this ?
The easiest fix is to log the data inside the second .then block, which then makes sure that the data is initialized and logged only after.
|
|
Summary
In short, promise is a easer and more cleaner way to write asynchronous functions , avoiding callback hell , more maintainable code and other many advantages over class callback functions!