简体   繁体   中英

Returning a promise using promise.all

I have 2 functions that resolve a promise and another 3rd constant that is simply an integer. Here I tried Promise.all in order to return promise resolved.

 const a = Promise.resolve('First returned'); const b = new Promise((resolve, reject) => { setTimeout(() => {resolve('second returned');}, 300); }); const c = 123; Promise.all([a,b,c]).then(response => { console.log(response); }); 

My question is, since the 3rd constant is simply an integer and doesn't resolve a promise, how it is included in the result. The result I get is ["First returned", "second returned", 123] .

If any item in the iterable object which is passed into the Promise is not an instance of the Promise, it will be ignored and passed to the then results using Promise.resolve method. Concise, it will be resolved automatically.

From the Documentation

If the iterable contains non-promise values, they will be ignored, but still counted in the returned promise array value (if the promise is fulfilled):

in Promose.all(...), if the iterables are non-promised values, there results will be either

  • Resolved by Default OR
  • Result will deduced based promised value

These 3 examples will make it clear

// resolved by default

let a = 100;
let b = 200;

Promise.all([a,b]).then(function(){
    console.log("Promised Resolved");
});

Inferred from the results - Resolved

// Resolved here
Promise.all([a,b, Promise.resolve("R-Text")]).then(function{
   console.log("R-Test Promise Resolved...");
}).catch(function(text){
   console.log("R-Test Promise Rejected...", text);
});

and Inferred from the results - Rejected

  // Rejected here
    Promise.all([a,b, Promise.resolve("R-Text"), Promise.reject("Rejected")]).then(function{
       console.log("R-Test Promise Resolved...");
    }).catch(function(text){
       console.log("R-Test Promise Rejected...", text);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM