【问题标题】:await in async is not working in typescript node [duplicate]异步等待在打字稿节点中不起作用[重复]
【发布时间】:2019-12-19 15:14:01
【问题描述】:

以下代码按预期使用超代理调用。阻止每个回调。在代码中 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;
}

【问题讨论】:

  • items.content是什么对象?
  • 很多代码我们不知道它的作用。 baseUrl.post().set().set().send() 是否返回承诺? collection.each() 是否返回承诺? collection.each() 是否为回调编码并返回一个承诺,以便它实际上会在该回调中等待 awaitsendRequest() 是否返回承诺?此外,如果fn() 返回一个承诺,return await fn() 等效于return fn(),而如果fn() 没有返回一个承诺,则await 毫无意义。
  • 而且,items.content.each() 会返回承诺吗?我问这一切是因为await 没有任何用处,如果你不等待一个似乎是一个非常非常常见的初学者错误的承诺(认为await 会等待任何东西,不管你给它什么)。
  • 我打赌 .each 是主要问题,但没有上下文,就不可能说

标签: node.js typescript async-await superagent


【解决方案1】:

从您的问题陈述中,我了解到您对 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;
}

【讨论】:

    猜你喜欢
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-05
    • 2020-06-11
    • 2022-01-22
    • 2018-05-03
    相关资源
    最近更新 更多