我希望在await循环结束后在扫描函数中调用回调函数。我怎样才能做到这一点?
let personObj = {};
let personArray = [];
async function scan() {
for await (const person of mapper.scan({valueConstructor: Person})) {
decrypt(person.name, function () {
personArray.push(personObj);
});
}
}
例如,我想在循环后调用console.log(personArray)
。
答案 0 :(得分:3)
您需要promisify the callback function在async
函数中使用它:
function decryptAsync(value) {
return new Promise(resolve => {
decrypt(value, resolve);
});
}
async function scan() {
let personArray = [];
for await (const person of mapper.scan({valueConstructor: Person})) {
let personObj = await decryptAsync(person.name);
personArray.push(personObj);
}
console.log(personArray)
}