NodeJS async.retry 获取未完成/获取后冻结

问题描述 投票:0回答:1

我正在尝试对 web-api 进行基准测试,但基准应用程序似乎在初始请求后没有继续。尝试运行代码时,doStressTest() 正常启动,并开始尝试从 web-api 获取数据,但似乎没有返回任何内容,可能是由于 fetch() 调用,parallelLimit( ) 函数,或者我对这两个框架的错误使用。这导致代码不会超过行

await async.parallelLimit(promises, limit)
,从而完全冻结应用程序。初始请求由经过测试的 web-api 接收并由 web-api 正确处理。

为什么代码会卡住,如何修复?

如果不使用,获取请求似乎会正确返回,例如运行以下代码片段将打印出“这正常完成”

fetch(`http://localhost:3000/users/1/cards`).then(() => {
    console.log("This completes normally");
});

如何为 X 立即运行基准测试以及它在哪里冻结

import async from "async";
import fetch from "node-fetch";

const users = [];
for(let i = 1; i <= 5000; ++i) {
    users.push(i);
}

function attemptFetches(limit) {
    // construct all promises
    let promises = [...users].map((user) => {
        // THESE ARE THE REQUESTS async.parallelLimit WILL RUN
        return () => async.retry(1000000, () => fetch(`http://localhost:3000/users/${user}/cards`));
    });

    const promise = new Promise(async (resolve, reject) => {
        const startTime = performance.now();
        // CODE RUNS UNTIL the line below \/
        await async.parallelLimit(promises, limit);
        // DOESN'T CONTINUE FROM HERE ON OUT
        const endTime = performance.now();
        resolve(endTime - startTime);
    });

    return promise;
}

压力测试是如何启动的

async function doStressTest() {
    result = await attemptFetches(10);
    console.log(`Running ${users.length} fetch queries in sets of 10 took ${result} ms`);
    result = await attemptFetches(100);
    console.log(`Running ${users.length} fetch queries in sets of 100 took ${result} ms`);
    result = await attemptFetches(1000);
    console.log(`Running ${users.length} fetch queries in sets of 1000 took ${result} ms`);
    result = await attemptFetches(5000);
    console.log(`Running ${users.length} fetch queries in sets of 5000 took ${result} ms`);
};

const i = setInterval(() => {
    // prevent node from killing process
}, 1000);

doStressTest().then(() => {
    clearInterval(i);
});

使用过的 npm 包文档: async.parallelLimit, async.retry, node-fetch

javascript node.js asynchronous async-await fetch-api
1个回答
2
投票

此行返回非异步函数:

return () => async.retry(1000000, () => fetch(`http://localhost:3000/users/${user}/cards`));

因此,您在

doStressTest()
中的等待调用不知道实际等待任何事情,因为它没有返回承诺。

如果您为每个匿名函数添加一个

async
,那么它将正常工作:

return async () => async.retry(1000000, async () => fetch(`http://localhost:3000/users/${user}/cards`));
© www.soinside.com 2019 - 2024. All rights reserved.