在异步中等待在打字稿节点中不起作用

时间:2019-08-13 05:02:38

标签: node.js typescript async-await superagent

以下代码按预期与超级代理之间不起作用。阻止每个回调。在代码中sendRequest没有被阻止;我在程序执行结束时看到空数组。

任何解决问题的帮助将不胜感激。谢谢

process();
async function process() {
    let data = await dataPreparation(collection);
    console.log("data", data);
}


async function sendRequest(endPath, request) {
    return await baseUrl.post(endPath)
        .set('Accept', 'application/json')
        .set('Content-Type', 'application/json')
        .send(request)
}


async function dataPreparation(collection) {
    let output = [];
    await collection.each(async (items) => {
        let tagName: string = items.name;
        await items.content.each(async (item) => {
            let rawRequest = item.request;
            let endPath = item.endPath;

            let response = await sendRequest(endPath, rawRequest);
            output.push({ 'request': rawRequest, 'endPath': endPath, 'response': response.status });

        })
    });
    return output;
}

1 个答案:

答案 0 :(得分:0)

从您的问题陈述中,我了解到您在使用foreach回调时遇到了问题,我已将其转换为for循环,我认为它应该可以工作。

async function dataPreparation(collection) {
    let output = [];
    for (var items of collection) {
        let tagName: string = items.name;
        for (var item of items.content) {
            let rawRequest = item.request;
            let endPath = item.endPath;
            let response = await sendRequest(endPath, rawRequest);
            output.push({ 'request': rawRequest, 'endPath': endPath, 'response': response.status });
        }
    };
    return output;
}