Reputation: 3
So I am new to Promise, I want to use Promise to do multiple url call. Now it seems that the algorithm works but the problem is that the riot api has a rate limit, so I have to let the program wait for a short time after each api call. How should I add this?
var matchidList = [];
for (var i = 0; i < pml.length; i++) {
matchidList.push(pml[i]["gameId"]);
}
var matchuri = "https://na1.api.riotgames.com/lol/match/v3/matches/";
var uris = [];
for (var i = 0; i < matchidList.length; i++) {
uris.push(matchuri + matchidList[i] + "?" + apikey);
}
Promise.map(uris, function(url) {
return rp.getAsync(url).spread(function(response,body) {
return JSON.parse(body);
});
}).then(function(results) {
// results is an array of all the parsed bodies in order
console.log(results);
tag.checkTags("").then((tags) =>{
res.render('index', { result: body,
val: search,
matches: ''
});
});
}).catch(function(err) {
console.log(err);
// handle error here
});
Upvotes: 0
Views: 977
Reputation: 135287
Without Bluebird
Those without bluebird and still looking for Promise.delay
can implement it a simple delayed Promise with ease
Promise.delay = (ms, x) =>
new Promise(r => setTimeout(r, ms, x))
const logp = p =>
p.then(console.log, console.error)
logp(Promise.delay(3000, 'a'))
logp(Promise.delay(2000, 'b'))
logp(Promise.delay(1000, 'c'))
// c
// b
// a
Upvotes: 2
Reputation: 707526
Since it looks like you're using Bluebird, you can use Promise.map()
s concurrency setting and you can use Promise.delay()
:
Promise.map(uris, function(url) {
return rp.getAsync(url).spread(function(response,body) {
return Promise.delay(200, JSON.parse(body));
});
}, {concurrency: 1}).then(...);
The concurrent setting will make Promise.map()
only run one request at a time and Promise.delay()
will chain a delayed promise to the rp.getAsync()
so that Promise.map()
won't go to the next iteration until the delay is done.
Upvotes: 1