gpt4 book ai didi

javascript - 将多个请求的结果保存到数组中

转载 作者:太空宇宙 更新时间:2023-11-04 02:48:21 24 4
gpt4 key购买 nike

我试图发出多个 API 请求并将响应存储到数组中。

数组保持为空,因为我不知道 for 循环的异步行为。

const results = [];

for (let i = 0; i < apiUrls.length; i++) {
apiCall(apiUrls[i], res => {
results.push(res);
});
}

console.log(results) // []

所以我将其重写为:

const results = []

async function makeApiCalls () {
for (const apiUrl in apiUrls) {
const res = await apiCall(apiUrl)
results.push(res)
}

console.log(results) // [data, someData, otherData...]
}

makeApiCalls()

它有效!但按顺序运行。我们可以改进它以并行运行,如下所示:

let results = []

async function makeApiCalls () {
const promises = []

// fire all requests
for (const apiUrl in apiUrls) {
promises.push(apiCall(apiUrl))
}

// wait until all promises are resolved and copy responses to array
results = [...await Promise.all(promises)];

console.log(results) // [data, someData, otherData...]
}

makeApiCalls()

最佳答案

循环异步调用不会很好地工作,因为您不知道何时完成以及 stats 数组已填充。您需要一些额外的机器来处理这个问题。在不使用 async 或 Promise 的情况下,基本思想是:

var stats = [];
var finishedCount = 0; // keep track of how many callbacks have completed

for (let i = 0; i<tempBackends.length; i++)
{

http.get(tempBackends[i], function(res) {

console.log("Received response: " + res.statusCode);

if(res.statusCode == 200) {
stats.push('OK');
console.log('pushed OK\n');
}
else {
stats.push('Not OK');
console.log('pushed Not OK\n');
}

// ADD LOGIC HERE TO HANDLE ALL CALLBACKS HAVING FINISHED
finishedCount++;
if (finishedCount === tempBackends.length) {
console.log("ALL DONE!! stats is", stats);
}

});
}

但是,使用这种方法,stats 数组将不会与 tempBackends 对齐。 stats 中值的顺序将基于异步调用完成的顺序。此外,这种风格的代码将很难维护。相反,您应该使用async或promise。 async 方法是:

async.map(
tempBackends,
function(backend, callback) {
http.get(backend, function(res) {
callback(null, res.statusCode === 200 ? "OK" : "Not OK");
});
function(err, data) {
console.log("ALL DONE!! stats is", data);
}
);

promise 方法更具可读性和可写性。首先,制作 http.get 的 promise 版本:

function getPromise(backend) {
return new Promise(function(resolve) {
http.get(backend, function(res) {
resolve(res.statusCode === 200 ? "OK" : "Not OK");
});
});
}

现在你可以写了

Promise.all(tempBackends . map(getPromise)) .
then(function(stats) {
console.log("ALL DONE!! stats is", stats);
});

关于javascript - 将多个请求的结果保存到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34592484/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com