如何在等待循环结束后调用回调函数

时间:2017-12-11 11:42:23

标签: javascript typescript

我希望在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)

1 个答案:

答案 0 :(得分:3)

您需要promisify the callback functionasync函数中使用它:

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)
}