What are JavaScript Promises?
We all have used asynchronous callbacks in our applications. We would need to wait for the result of an asynchronous operation to proceed. Earlier we have used callbacks for achieving this, but faced a lot of difficulties. Promise helps us in making this Asynchronous operation Synchronous.
Promise can be considered as a placeholder or container for storing the result from an asynchronous operation.
A promise can be in any of the below states,
- Pending - This will be the initial state and the asynchronous operation is in process.
- Resolved or fulfilled - The operation is completed successfully and returns the results as a Promise object.
- Rejected - Operation is failed.
Example
- var message1 = function(msg) {
- return new Promise((resolve, reject) => {
- if (msg) {
- resolve(msg);
- } else {
- reject(Error("Invalid string"));
- }
- });
- };
- var message2 = function(msg) {
- return new Promise((resolve, reject) => {
- if (msg) {
- resolve(msg);
- } else {
- reject(Error("Invalid string"));
- }
- });
- };
- var message3 = = function(msg) {
- return new Promise((resolve, reject) => {
- if (msg) {
- resolve(msg);
- } else {
- reject(Error("Invalid string"));
- }
- });
- };
- message1("First Promise Resolved").then((result) => {
- console.log(result);
- return message2("Second Promise Resolved");
- }).then((result) => {
- console.log(result);
- return message3("Third Promise Resolved");
- }).then((result) => {
- console.log(result);
- }).catch((err) => {
- console.log(err);
- });
We can chain multiple asynchronous operations using then call back as above. But the real problem came into the picture when we need to use asynchronous calls inside a loop. In that case, we can use the static method Promise. all().
Promise.all() static method
This method accepts a list of promises and returns a single promise. This single promise will get resolved only when all input promises are resolved and will be in a rejected state if any of the input promises is rejected.
Example
- let tmpArray = [1, 2, 3, 4];
- let promiseArray = [];
- private getData(id) {
- return new Promise((resolve, reject) => {
- fetch("testapi/" + id).then(r =>
- return r.json()).then((data) => {
- resolve(data.value);
- });
- });
- }
- private resolvePromises() {
- tmpArray.forEach(
- (id) => {
- promiseArray.push(getData(id));
- });
- Promise.all(promiseArray).then((results) => {
- results.forEach(
- (result) => {
- console.log(result);
- });
- });
- }