2017-04-05 111 views
0

是否有方法爲Promisee.all中的每個結果分配一個名稱?節點JS Promise.all()結果命名

比方說,這是我的代碼:

Promise.all([getBalls, getKids, getTeams]) 
.then(function (results) { 
    const new_team = doSomething(results[0], results[1],results[2]) 
    resolve(new_team); 
}); 

而且我希望它是這樣的:

Promise.all([ 
    balls: getBalls, 
    kids: getKids, 
    teams: getTeams 
]).then(function (results) { 
    const new_team = doSomething(balls,kids,teams) 
    resolve(new_team); 
}); 
+1

你所要求的長相酷似藍鳥的該API'Promise.props()':http://bluebirdjs.com/docs/api/promise.props.html。你傳入一個像你指定的對象(除非不在數組中),並且返回具有相同鍵的對象的結果。 – jfriend00

+0

謝謝@ jfriend00這真的很酷,但不是我正在尋找的東西。 –

+0

你是什麼意思「不是你在找什麼」?它完全符合你的要求。 'Promise.all()'不會像你所問的那樣工作,所以你將需要新的代碼來獲得這樣工作的函數。 – jfriend00

回答

2

您可以使用ES2015的Array destructuring.then回調函數:

Promise.all([ 
    getBalls, 
    getKids, 
    getTeams 
]).then(function ([ balls, kids, teams ]) { // <= notice the function parameters 
    const new_team = doSomething(balls, kids, teams); 
    resolve(new_team); 
}); 
+0

Thanks @Arnelle Balane –

+0

@HatzavWolff沒問題,很高興幫助:) –

0

在最近的node.js(>node v6.x)版本中,可以使用destructu環和做

Promise.all([getBalls, getKids, getTeams]) 
.then(function ([balls, kids, teams]) { 
    const new_team = doSomething(results[0], results[1],results[2]) 
    resolve(new_team); 
}); 
+0

謝謝@ThomasThiebaud! –

0

也許Promise.props看起來更容易處理。 http://bluebirdjs.com/docs/api/promise.props.html

Promise.props({ 
    balls: getBalls, 
    kids: getKids, 
    teams: getTeams 
}) 
.then((results) => { 
    const new_team = doSomething(results.balls, results.kids, results.teams) 
    resolve(new_team); 
});