NodeJS承诺解决

时间:2016-12-31 21:07:47

标签: javascript node.js promise

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();

为什么我还需要另一个<{1}}?

我读到当你有{return res;}时,必须附加另一个return (something),但这不是这里的情况。帮助

2 个答案:

答案 0 :(得分:3)

Promise.all期待一系列承诺。 .then返回一个承诺。因此,您的映射逻辑会将数字数组转换为Promises数组,这正是您所需要的。

.then((res) => {return res;})完全没必要,return f();就足够了。您甚至可以将当前代码进一步简化为:

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

我看到当return (something)内有then时,必须附加另一个

这与.then无关。 .then只是返回一个承诺。要访问承诺的结果,您需要通过.then附加处理程序。

您不需要在此处执行此操作,因为您将承诺传递给Promise.all。您正在通过.then((result)=>{console.log(result)})访问 结果。

答案 1 :(得分:0)

  

为什么我不需要另一个附加到{return res;}这里?

     

我读到当你有一个return (something)时,另一个   必须附上then,但不是这里的情况。帮助

.then()附加了另一个Promise.all()。您是说应该附加.catch()以避免Uncaught (in promise)

另请注意,Promise.all()来自return来自g() Promise.then()进一步链接.catch()

.map()回调中链接的{p> PromisePromise可用于处理错误或被拒绝.then()并将已解决的Promise.all()返回至throw链接到Error();或Promise.all()当前或新的.map().then()来电。

该模式还可用于返回传递给.catch()的所有承诺,无论是已解决还是拒绝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));链接到{{1}}。

{{1}}