In JavaScript, callback functions were initially used to handle asynchronous operations. However, callbacks were limited in terms of functionality and often led to confusing code, so, promises were introduced to cater to these problems. According to MDN, “the Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.”
A promise object has one of three states:
promise
is created using a constructor that takes a call back function with two arguments (line 1).then()
method is called when the promise is resolved, and the catch()
method is called if the promise is rejected or if there was an error during the code execution (lines 10-11).Promise.all()
The Promise.all()
method returns a single promise that resolves when all of the passed-in promises have resolved. It rejects if one of the promises is rejected.
Promise.race()
The Promise.race()
method returns a promise that resolves or rejects as soon as one of the promises resolves or rejects. The fromRes
method contains the value from the promise that is resolved first.
Free Resources