Reputation: 3
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()?
Upvotes: 0
Views: 43
Reputation: 707158
Use an http request library that works with promises such as 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.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.run()
function is any one request has an error. 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.Upvotes: 1
Reputation:
You can use axios()
or got()
and etc.
And please try like this:
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);
}
Upvotes: 0