通用承诺重试逻辑 [英] Generic promise retry logic
本文介绍了通用承诺重试逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图弄清楚如何创建一个通用的重试函数,该函数以指数形式退回传递给它的任何诺言.除了几件事,看起来一切都在工作.如果函数在第一次尝试时就解决了,那么我会看到我的resolve值,它会退出hey,这是预期的.如果在任何后续呼叫中都解决,则不会注销嘿.如果拒绝,我会收到一些尚未考虑的弃用警告.这是代码...
I am trying to figure out how to create a generic retry function that exponentially backs off for any promise passed to it. It looks like everything is working except for a couple things. If the function resolves on the first try, then I see my resolve value and it logs out hey which is expected. If it resolves on any subsequent call, it does not log out hey. If it rejects, I get a couple deprecation warnings which I haven't looked into yet. Here is the code...
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'));
这篇关于通用承诺重试逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文