gpt4 book ai didi

javascript - promise 延迟实现

转载 作者:行者123 更新时间:2023-12-01 01:52:14 25 4
gpt4 key购买 nike

我尝试通过这种方式实现 Promise 的延迟:

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 调用以避免速率限制问题。这似乎并没有真正起作用,因为我全部都被一堆执行了。

最佳答案

我有一个几年前编写的简单的速率有限的 promise 队列,它对我很有用

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));
}

关于javascript - promise 延迟实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51380824/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com