我尝试通过这种方式在Promises中实施延迟:
function postAndSetContentfulId (client, code) {
return delay().then(_ => {
return postToContentful(client, code).then(setCode)
})
}
function delay () {
let multipler = Math.floor((count++) / 100) + 1
let milliseconds = multipler * 2000
return new Promise(resolve => setTimeout(() => resolve(), milliseconds))
}
我需要延迟第三方API调用以避免速率限制问题。这似乎实际上不起作用,因为我一堆都被执行了。
答案 0 :(得分:2)
我有一个几年前写的简单的限价承诺承诺队列,对我很有帮助
const rateLimited = perSecond => {
const milliSeconds = Math.floor(1000 / perSecond);
let promise = Promise.resolve(Date.now());
return fn => promise.then(lastRun => {
const wait = Math.max(0, milliSeconds + lastRun - Date.now());
promise = promise.then(() => new Promise(resolve => setTimeout(resolve, wait))).then(() => Date.now());
return promise.then(() => fn());
});
};
const example = rateLimited(2); // 2 per second for the example
let allPromises = Array.from({length:10}, (_, i) => i)
.map(v => example(() => Promise.resolve(v)));
console.time('Elapsed');
console.log('Started - should take 5 seconds');
Promise.all(allPromises).then(results => {
console.log(results);
console.timeEnd('Elapsed');
});
对于您的代码,您将像使用rateLimited
const q = rateLimited(20); // 20 per second limit for example
function postAndSetContentfulId(client, code) {
return q(() => postToContentful(client, code).then(setCode));
}