承诺 - 尝试直到成功 [英] Promise - try until it succeds

查看:31
本文介绍了承诺 - 尝试直到成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用原生 node.js 的 Promises 和问题这里确实给了我任何观点.基本上,我有如下功能:

I'm using native node.js's Promises and the question here did give me any point. Basically, I have a function like below:

var foo = foo (resolve, reject) {
    return obj
        .doA()
        .doB()
        .then(function (value) {
            // here I choose if I want to resolve or reject.
        })
        .catch(function(err) {
        });
}

var promise = new Promise(foo);

return promise
    .then(function() {
        // I know here what I have to return.
    })
    .catch(function(err){
        // I want to repeat the foo function until it is resolved and not rejected. 
    })

obj 是一个承诺的对象.只要兑现了承诺,我就想重试 foo 函数;如果被拒绝,请重试.

obj is a promised object. I would to like to retry the foo function as long as the promise is fulfilled; if it's rejected, then try again.

我不知道如何构建链.有什么帮助吗?谢谢.

I do not know how to structure the chain. Any help? Thanks.

推荐答案

尝试在 foo 的声明中包含 function ,使用递归

Try including function in declaration of foo , using recursion

function foo() {

  var n = String(new Date().getTime()).slice(-1);
  // if `n` < 5 reject `n` , else resolve `n`
  return Promise[n < 5 ? "reject" : "resolve"](n)
    .then(function(value) {
      return value
        // here I choose if I want to resolve or reject.
    })
    .catch(function(err) {
      return Promise.reject(["rejected", err])
    });
}

(function repeat() {
  var promise = Promise.resolve(foo());

  return promise
    .then(function(data) {
      console.log("complete", data)
        // I know here what I have to return.
    })
    .catch(function(err) {
        // I want to repeat the foo function until it is resolved and not rejected. 
      console.log(err);
      if (err[0] === "rejected") repeat()
    })
}())

这篇关于承诺 - 尝试直到成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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