2016-12-31 125 views
3
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(); 

为什么我不需要另外再连接到{return res;}这里?承诺的NodeJS分辨率

我读到,当你有一个return (something)在一个然后,另一个then必须附加,但它不是这里的情况。帮帮我?

+1

的承诺将弄清楚,如果你打算地图,或者flatMap。所以你可以返回一个普通的值,它会映射;返回一个承诺,它会flatMap。 – elclanrs

回答

3

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

.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)})结果

+0

为什么在“地图(f)”中忽略了“返回”? – user7361276

+0

因为'(member)=> {return f();}'在你的例子中等价于'f'。或者更一般的:给定'function foo(){};函数bar(){return foo(); }'然后调用'bar()'和直接调用'foo()'完全一样。在你的例子中,不需要中间函数'(member)=> {return f();}',你可以直接将'f'传递给'a.map'。 –

0

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

我读到,当你有一个return (something)在一个然后,另一个 then必须附加,但它不是这里的情况。帮帮我?

还有另一个.then()附于Promise.all()。你是否应该附加.catch()以避免Uncaught (in promise)

还请注意,Promise.all()不是return编号从g()调用,以进一步链接Promise

.then().catch().map()回调中链可被用于任一手柄错误或拒绝Promise并返回一个解决Promise.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));