NodeJS promise resolution

2019-07-03 22:47发布

问题:

const a = [1, 2, 3, 4, 5];

const f = () => new Promise((resolve, reject) => resolve(4));

const g = () => {
  Promise.all(a.map((member) => f().then((res) => res)))
    .then((result) => {
      console.log(result)
    });
}

g();

Why do I not need another then attached to {return res;} here?

I read that when you have a return (something)inside a then, another then must be attached, but its not the case here. Help?

回答1:

Promise.all expects an array of promises. .then returns a promise. Therefore your mapping logic converts an array of numbers to an array of promises, exactly what you need.

.then((res) => {return res;}) is completely unnecessary btw, return f(); would suffice. You can even simplify your current code further to:

Promise.all(a.map(f)).then(result => console.log(result));

I read that when you have a return (something) inside a then, another then must be attached

This has nothing to do with .then. .then simply returns a promise. To access the result of a promise you need to attach a handler via .then.

You don't need to do this here because you are passing the promises to Promise.all. You are accessing that result via .then((result)=>{console.log(result)}).



回答2:

Why do I not need another then attached to {return res;} here?

I read that when you have a return (something)inside a then, another then must be attached, but its not the case here. Help?

There is another .then() attached to Promise.all(). Did you mean .catch() should be attached to avoid Uncaught (in promise)?

Note also, Promise.all() is not returned from g() call, to further chain the Promise.

.then() and .catch() chained within .map() callback can be utilized to either handle error or rejected Promise and return a resolved Promise to .then() chained to Promise.all(); or to throw current or new Error() to Promise.all() call.

The pattern can also be used to return all promises passed to .map(), whether resolved or rejected to .then(), without immediately calling .catch() chained to Promise.all().

function  f (index) {
   return new Promise(function (resolve, reject) {
        if (index !== 4) resolve(4);
        else reject("err at index " + index)
    })
}

var a =[1, 2, 3, 4, 5];

function  g () {
    return Promise.all(a.map((member, index)=>{
        return f(index).then((res) => {return res;})
              .catch(e => {console.log(e); throw new Error(e)})
    }))
    .then((result)=>{console.log(result); return result})
    .catch(e => {
      // handle error here, return resolved `Promise`,
      // or `throw new Error(e)` to propagate error to
      // `.catch()` chained to `g()` call
      console.log("handle error within g", e); 
      return "error " + e.message + " handled"});
}

g()
.then(data => {console.log(data) /* `error err at 4 handled` */ })
.catch(e => console.log("done", e));