重试失败的异步/承诺功能?

mbi*_*nov 5 javascript asynchronous node.js promise

我有这个异步块:

test().then(function(result){
    // Success: Do something.
    doSomething();
}).catch(function(error){
    // Error: Handle the error, retry!
    // How to re-run this whole block?
});
Run Code Online (Sandbox Code Playgroud)

我可以跟踪的successfailed成果。但是,test().then().catch()如果我们失败了,是否可以重试整个链?并继续重试直到条件解决?

Fra*_*ica 5

如果可以切换到async/await语法,则可以使用while循环:

let keepTrying;

do {
    try {
        await test();
        keepTrying = false;
    } catch {
        keepTrying = true;
    }
} while (keepTrying)

doSomething();
Run Code Online (Sandbox Code Playgroud)

然后,您可以将重试逻辑抽象为自己的函数以供重用。


Cer*_*nce 2

您可以将整个事情放入一个函数中,如果catch进入该块,该函数会递归地调用自身:

function tryTest() {
  return test().then(function(result) {
    // Success: Do something.
    doSomething();
  }).catch(function(error) {
    // error handling

    // make sure to return here,
    // so that the initial call of tryTest can know when the whole operation was successful
    return tryTest();
  });
}


tryTest()
  .then(() => {
    console.log('Finished successfully');
  });
Run Code Online (Sandbox Code Playgroud)

如果您doSomething可以接受result参数,并且如果tryTest不接受任何参数,则可以将上面的内容简化为:

function tryTest() {
  return test()
    .then(doSomething)
    .catch(tryTest);
}


tryTest()
  .then(() => {
    console.log('Finished successfully');
  });
Run Code Online (Sandbox Code Playgroud)