您有两个主要问题。
您的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
});
运作方式如下: