您有两个主要问题。
您的
phoneNumber
变量将不是您想要的变量。可以通过更改 数组的.forEach()
或.map()
迭代来解决此问题,因为这将为当前变量创建局部函数作用域。您已经创建了一种方法来知道所有异步操作何时完成。有很多重复的问题/答案显示了如何执行此操作。您可能要使用
Promise.all()
。
我建议这种解决方案利用您已经拥有的承诺:
function getContactList(contacts) { var contactList = {}; return Promise.all(contacts.filter(utils.isValidNumber).map(function(phoneNumber) { return db.client().get(phoneNumber).then(function(reply) { // build custom object constactList[phoneNumber] = reply; }); })).then(function() { // make contactList be the resolve value return contactList; });}getContactList.then(function(contactList) { // use the contactList here}, funtion(err) { // process errors here});运作方式如下:
- 调用
contacts.filter(utils.isValidNumber)
以将数组过滤为仅有效数字。 - 调用
.map()
以遍历该过滤后的数组 return db.client().get(phoneNumber)
从.map()
回调创建一个promise数组。- 获取电话号码的数据后,将该数据添加到您的自定义
contactList
对象中(这实际上是.map()
循环的副作用。 Promise.all()
在返回的promise数组上使用,以了解它们何时完成。- 使
contactList
我们建立的对象成为返回的Promise的resolve值。 - 然后,要调用它,只需使用返回的promise
.then()
即可获得最终结果。当您已经承诺可以返回时,无需添加回调参数。



