我有一个程序可以执行此操作:
async function run() {
for (i of object) {
request("https://www." + i + ".mydomain.com")
await wait(250) // synchronous, to prevent API spam
}
// HERE
moveOn()
}
在运行 moveOn() 之前如何等待所有请求的响应?
答案 0 :(得分:1)
使用可与 got()
等承诺一起使用的 http 请求库:
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()
}
这里还有一些其他相关要点。
request()
库已deprecated,不推荐用于新代码。got()
,它支持 request()
库所做的大多数选项,但将一些东西包装在更容易使用的基于 Promise 的 API 中(在我看来)并且非常支持未来的发展。run()
函数。如果您想做一些不同的事情,您需要使用 await got()
从 try/catch
捕获错误,然后在 catch
块中处理错误。答案 1 :(得分:0)
您可以使用 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);
}