[英]Run through an array making post requests in an asynchronous manner - Javascript
我目前正在尝试向另一个页面发出多个发布请求以运行功能服务器端。 因为这些请求是 API 调用的一部分,所以响应时间会因调用而异。 所以我试图从一个数组中运行调用,其中调用将在触发下一个请求之前等待来自函数的响应。 目前所有调用都在同一时间完成,因为我使用了forEach
循环。
function update() {
ints.forEach(value => {
call(value['int']);
});
location.reload();
}
function call(value) {
$.post('PATH TO API CALL'
).success(function (resp) {
$.post('PATH TO FUNCTION'
).success(function (resp) {
// function returns true when completed
});
});
}
我希望函数“update”通过函数“call”运行,等待它已经完成的函数“call”的响应。 任何帮助将不胜感激。
最简单的调整是使两个函数都async
,以便您可以在for
循环中await
每个call
(并且call
也await
每个.post
):
async function update() {
for (let i = 0; i < ints.length i++) {
// the array will be iterated through serially,
// waiting for the previous call to complete before sending out another
await call(ints[i]);
}
// the next line will only run once all iterations have finished:
location.reload();
}
async function call(value) {
const resp1 = await $.post('PATH TO API CALL' ...);
// do stuff with resp1, if needed
const resp2 = await $.post('PATH TO FUNCTION', ...)
// do stuff with resp2, if needed
}
还要确保在update
的消费者中使用.catch
来处理可能抛出的任何错误。
@CertainPerformance 提供的答案当然有效。 但是,这是我将如何做到的。
代替运行的for
循环和执行在瀑布方式每个单独的请求,我会建立一个array
的promises
,然后在与一次执行它们Promise.all
。 如果您确实需要以瀑布方式运行承诺(下一次调用需要来自前一个值的响应),那么Promise.all
可能不是最好的选择。 在所有其他情况下,我会改用它。
// Some method that is actually running the request and returning the response async function executeHttpRequest(id) { const response = await fetch(`https://reqres.in/api/users/${id}`); return response.json(); } // Just a quick way to build up an array of promises. async function callThisManyThings(num) { const promises = Array(num).fill(null).map( async (x, i) => executeHttpRequest(i) ); const results = await Promise.all(promises); console.log(results); } callThisManyThings(10);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.