Another Promise
Hey guys, I hope you are all doing great.
In one of my last posts, I talked about Promise in Asynchronous JavaScript, so today I would love to talk about another way of calling promise to improve responsiveness and reduce waiting time in web loading
Let's consider running some lines of code that are independent of one another to show another type of Promise apart from the common one, that is promises.all.
Unlike the normal one, That will all run together (i.e fetchData1(),fetchData2() and fetchData3() without using Promise.all ) but one after the other, which in turn leads to a bad site experience, I.e., the time it takes to load all the site content will be long, which would defame our work. So, to prevent such actions, we have other ways of making our promises which is...
Promise.all()
Promise.all ( ).
This takes in iterations( like arrays of promises e.g on line 164 to 184 of the code) which will then return a new promise which will then run them all parallel to each other not simultaneously. like this code below
Promise.all([fetchData1(),fetchData2(),fetchData3()])
One thing about this is that if a single promise gets rejected, all the rest will be rejected too.to prevent this, we can chain it by the then() method too(if those promises depend on each other to prevent the error).
But of Promise.all:
Sequential Dependencies: If one Promise depends on the result of another, it might not be suitable. In such cases, chaining Promises might be more appropriate.
Error Handling: If one Promise is rejected, the entire
Promise.all()
operation will be rejected. Careful error handling is crucial.
so next time while coding, knowing when to use this promise can be life saver.
HAPPY CODING……