重试javascript中的Promise的一般解决方案 [英] general solution to retry a promise in javascript

查看:82
本文介绍了重试javascript中的Promise的一般解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试给出重试承诺的一般解决方案。以下是我的处理方式,并出现未捕获(承诺)错误。

I try to give out a general solution for retrying a promise. Below is my way and comes an error of "Uncaught (in promise)".

如何解决此问题?

function tryAtMost(maxRetries, promise) {
  let tries = maxRetries

    return new Promise(function(resolve, reject) {
        promise.then((result) => {
        resolve(result)
      })
        .catch(err => {
            if (tries > 0) {
                console.log(`tries with ${tries}`)
          tryAtMost(--tries, promise);
        } else {
          reject(err)
        }
        })
    })
}

tryAtMost(3, promise).then(result => {
  console.log(result)
})
.catch(err => {
  console.log(err)
})


推荐答案

您所要求的原因是您缺少对解决在您的渔获 c中:

The reason for what you asked about is that you're missing a call to resolve in your catch:

.catch(err => {
    if (tries > 0) {
        console.log(`tries with ${tries}`);
        resolve(tryAtMost(--tries, promise)); // <=== ****
    }
    else {
        reject(err)
    }
})

...因此您创建的承诺永远不会被任何事物处理,因此,如果它被拒绝,您将得到未处理的承诺

...and so you're creating a promise that is never handled by anything, and so if it rejects, you'll get an unhandled rejection.

但是 tryAtMost 有一个问题:它无法使用您提供的信息,因为它不知道尝试什么。您需要将执行者而不是承诺传递给它,因为您需要重试执行者的工作。这也使函数简单得多:

But, tryAtMost has a problem: It cannot work with the information you've given it, because it doesn't know what to try. You need to pass it an executor, not a promise, because it's the work of the executor that you need to retry. This also makes the function a lot simpler:

function tryAtMost(tries, executor) {
    --tries;
    return new Promise(executor)
        .catch(err => tries > 0 ? tryAtMost(tries, executor) : Promise.reject(err));
}

使用:

tryAtMost(4, (resolve, reject) => {
    // The thing to (re)try
});

示例:

function tryAtMost(tries, executor) {
  console.log(`trying, tries = ${tries}`);
  --tries;
  return new Promise(executor)
    .catch(err => tries > 0 ? tryAtMost(tries, executor) : Promise.reject(err));
}

tryAtMost(4, (resolve, reject) => {
  const val = Math.random();
  if (val < 0.3) {
    resolve(val);
  } else {
    reject(val);
  }
})
.then(result => console.log(result))
.catch(err => console.error(err));

这篇关于重试javascript中的Promise的一般解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆