gpt4 book ai didi

javascript - 通用 promise 重试逻辑

转载 作者:行者123 更新时间:2023-11-29 23:22:14 30 4
gpt4 key购买 nike

我正在尝试弄清楚如何创建一个通用的重试函数,该函数对传递给它的任何 promise 呈指数回退。看起来一切正常,除了几件事。如果该函数在第一次尝试时解析,那么我会看到我的解析值并且它会注销,这是预期的。如果它在任何后续调用中解决,它不会注销嘿。如果它拒绝,我会收到一些我尚未研究过的弃用警告。这是代码...

function retry(func, max, time) {
console.log(max);
return new Promise((resolve, reject) => {
func()
.then(r => resolve(r))
.catch(err => {
if (max === 0) {
reject(err);
} else {
setTimeout(function(){
retry(func, --max, time * 2);
}, time);
}
});
});
}

const promise = retry(function () {
return new Promise((resolve, reject) => {
const rand = Math.random();
if (rand >= 0.8) {
resolve('hey');
} else {
reject(new Error('oh noes'));
}
});
}, 5, 100);

promise.then(r => console.log(r)).catch(err => console.log(err));

如有任何帮助,我们将不胜感激。

最佳答案

这是一个工作示例

/**
* Function to retry
*/
function retry(func, max, time) {
return new Promise((resolve, reject) => {
apiFunction()
.then(resolve)
.catch(err => {
if (max === 0) {
return reject(err);
} else {
setTimeout(function() {
retry(func, --max, time * 2)
.then(resolve)
.catch(reject);
}, time);
}
});
});
}

/**
* Function to test out
*/
const apiFunction = () => new Promise((resolve, reject) => {
const rand = Math.random();

if (rand >= 0.8) {
console.log('Works');

resolve('hey');
} else {
console.log('fail');

reject(new Error('oh noes'));
}
});

retry(apiFunction, 5, 10)
.then(() => console.log('all done ok'))
.catch(() => console.log('all done error'));

关于javascript - 通用 promise 重试逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50262211/

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