[英]Wait until all request calls are returned before continuing
I have a program which runs does this:我有一个运行的程序:
async function run() {
for (i of object) {
request("https://www." + i + ".mydomain.com")
await wait(250) // synchronous, to prevent API spam
}
// HERE
moveOn()
}
How do I wait until I have gotten a response from all requests before running moveOn()?在运行 moveOn() 之前,如何等到我得到所有请求的响应?
Use an http request library that works with promises such as got()
:使用 http 请求库,该库与诸如
got()
之类的承诺一起使用:
const got = require('got');
async function run() {
let promises = [];
for (let i of object) {
promises.push(got("https://www." + i + ".mydomain.com"));
await wait(250) // slight delay, to prevent API spam
}
let results = await Promise.all(promises);
// HERE
moveOn()
}
A couple other relevant points here.这里还有其他一些相关点。
request()
library has been deprecated and is not recommended for new code. request()
库已被弃用,不推荐用于新代码。got()
and it supports most of the options that the request()
library does, but wraps things in a bit easier to consume promise-based API (in my opinion) and is well supporting going forward.got()
,它支持request()
库所做的大多数选项,但更容易使用基于 Promise 的 API (在我看来)并且很好地支持前进。run()
function is any one request has an error.run()
function 是任何一个请求都有错误。 If you want to do something differently, you need to capture an error from await got()
with try/catch
and then handle the error in the catch
block.try/catch
从await got()
捕获错误,然后在catch
块中处理错误。You can use axios()
or got()
and etc. And please try like this:您可以使用
axios()
或got()
等。请尝试这样:
async function run() {
let count = 0;
for (i of object) {
axios("https://www." + i + ".mydomain.com")
.then(res => {
count++;
// Your code
})
.catch(err => {
count++;
});
await wait(250) // synchronous, to prevent API spam
}
// HERE
setInterval(() => {
if (count === object.length) {
count = 0;
moveOn()
}
}, 250);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.