在javascript中,一个返回promise并重试内部异步过程最佳实践的函数 [英] In javascript, a function which returns promise and retries the inner async process best practice

查看:29
本文介绍了在javascript中,一个返回promise并重试内部异步过程最佳实践的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,它返回一个 javascript Promise 并在其中运行一些异步代码.异步代码需要重试几次,以防失败.我一直在这样做,直到我观察到一些奇怪的行为,这让我怀疑我是否做得对.所以我不得不改变它.截断的两种方法都在这里.我知道为什么第一种方法 (asyncFunc) 不起作用,如果有人能分享一些关于它的技术清晰度,我将不胜感激.对于第二种方法 (ayncFunc_newer),您有没有关于如何做得更好的建议?

I have a function which returns a javascript Promise and inside it there runs some asynchronously code. The async code, needs to be retried for couple of times in cases it fails. I was doing that, till I observed some strange behaviors which made me wonder if I'm doing it right. So I had to change it. Both approaches snipped are down here. I have some idea why the first approach (asyncFunc) doesn't work, I would appreciate if someone could share some technical clarity about it. And for the second approach (ayncFunc_newer) any suggestion on how it can be done better?

var _retryCount = 0;

// this is what I was doing
function asyncFunc () {
	return new Promise(function(fulfill, reject) {
		doAsync()
			.then(fulfill)
			.catch(retry);

		function retry(promiseResult) {
			if(_retryCount < 3) {
				_retryCount++;
				return asyncFunc();
			}
			else {
				reject(promiseResult);
			}
		}
	});
}

// this what I'm doing now
function ayncFunc_newer() {
    return new Promise(function(fulfill, reject) {
        var retryCount = 0;

        doAsync()
            .then(fulfill)
            .catch(onReject);

        function onReject(bmAuthError) {
            if(retryCount < 3) {
                retryCount++;
                logWarning(error);
                
                doAsync()
                	.then(fulfill)
                	.catch(onReject);
            }
            else {
                fulfill(false);
            }
        }
    });                 
};

推荐答案

最佳实践是避免 promise 构造函数反模式.基本上,new Promise 的存在主要是为了包装 non-promise API,所以如果你的函数已经返回 promise,那么通常有一种方法可以避免使用它.

Best practice is to avoid the promise constructor anti-pattern. Basically, new Promise exists mostly to wrap non-promise APIs, so if your functions already return promises, then there's usually a way to avoid using it.

如果您的重试次数较少,那么您的情况很简单:

If you're doing a low fixed number retries, then your case is as simple as:

function ayncFunc() {
  return doAsync().catch(doAsync).catch(doAsync).catch(doAsync);
};

对于可配置的重试次数,您可以将其扩展为:

For a configurable number of retries, you'd expand this to:

var retries = 3;

function ayncFunc() {
  var p = doAsync();
  for (var i = 0; i < retries; i++) {
    p = p.catch(doAsync);
  }
  return p;
};

或者对于更多的重试次数,您可以使用递归方法:

Or for higher number of retries, you could use a recursive approach:

function ayncFunc() {
  function recurse(i) {
    return doAsync().catch(function(e) {
      if (i < retries) {
        return recurse(++i);
      }
      throw e;
    });
  }
  return recurse(0);
};

var console = { log: msg => div.innerHTML += msg + "<br>" };

function doAsync() {
  console.log("doAsync");
  return Promise.reject("Nope");
}

function ayncFunc() {
  return doAsync().catch(doAsync).catch(doAsync).catch(doAsync);
};

var retries = 3;

function ayncFunc2() {
  var p = doAsync();

  for (var i=0; i < retries; i++) {
    p = p.catch(doAsync);
  }
  return p;
};

function ayncFunc3() {
  function recurse(i) {
    return doAsync().catch(function(e) {
      if (i < retries) {
        return recurse(++i);
      }
      throw e;
    });
  }
  return recurse(0);
};

ayncFunc().catch(function(e) { console.log(e); })
.then(ayncFunc2).catch(function(e) { console.log(e); })
.then(ayncFunc3).catch(function(e) { console.log(e); });

<div id="div"></div>

这篇关于在javascript中,一个返回promise并重试内部异步过程最佳实践的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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