我正在尝试编写一个函数,直到函数内部的Promise得到解决,该函数才返回其值。这是我要执行的操作的简化示例。
'use strict';
function get(db, id) {
let p = db.command('GET', 'group:${id}');
p.then(g => {
g.memberNames = [];
g.members.forEach(id => {
User.get(db, id)
.then(profile => g.memberNames.push(profile.name))
.catch(err => reject(err));
});
return g;
});
}
该函数请求一个组ID,并返回该组的数据。在此过程中,它还将用户名扔到数据结构中以显示其名而不是用户ID。我的问题是,这是异步运行的,将跳过.then回调。到返回g时,尚未调用任何回调,并且
g.memberNames
仍为空。有没有办法让函数等待返回g,直到所有回调都被调用?我已经看到了很多有关等待的内容。这里有必要吗?将其他库添加到我的项目中是非常不希望的。
最佳答案
由于返回所有配置文件名称的操作也是异步的,因此当所有其他异步操作完成(或者其中一个操作被拒绝)时,您应该返回一个已兑现的Promise,该操作已通过Promise.all
完成
function get(db, id) {
let p = db.command('GET', 'group:${id}');
return p.then(g => {
return Promise.all(g.members.map(id => {
// NOTE: id is shadowing the outer function id parameter
return User.get(db, id).then(profile => profile.name)
})
})
}