A Promise object represents the future result of an asynchronous operation.
A promise is always in one of these states:
- pending: initial state, not fufilled or rejected.
- fulfilled: the operation completed successfully
- rejected: the operation failed :(
Once instantiated, the Promise is said to be in the “pending” phase. Once the phase is “fufilled”, a callback can be applied to the resolved value, which can return a new promise. Promises allows us to write asynchronous code in a synchronous way.
You can instantiate a
new Promise() object and pass it a callback to perform async computations. This callback has two arguments:
reject. Both of which, are passed later passed as callbacks in the
When the Promise has “fufilled”, the resolve callback will be applied to a value. If the Promise returns an error, the
reject callback is invoked.
Where do the resolve and reject callbacks come from?
The resolve callback is passed through the Promise object’s
The reject callback is passed through the Promise object’s
1) Create a new promise:
Note: randomIntApi just returns an integer after some seconds
2) Promise is invoked, and is pending… once complete will invoke the callback passed to
3) Pass a callback to the Promise’s
.then() method which will be applied on the resolved value:
Promise in action using .fetch() API
As an aside, if you return another Promise object in the callback, you can chain Promises: