Javascript 在承诺链上来回前进的模式

Javascript pattern for going back and forward on a promise chain

我学会了喜欢和使用承诺链。但是有时我需要重复执行中的一个阶段。有没有办法在不将承诺链分解为单独的方法的情况下做到这一点?

dataLayer.loginUser(loginData)
    .then(function (response) {

         console.log('loginUser response -> ', response);
         return dataLayer.getData();

    }.bind(this))
    .then(function (response) {

         console.log('loginUser response -> ', response);
         if (response.message === 'JWT_EXPIRED') {
             // Somehow go back to the previous stage
             return dataLayer.refreshJWT().then(...);
         }

      // next stage
      return ...
    });

不,没有。您将需要一个单独的函数,您可以参考并再次调用。

当然,您可以只使用命名函数表达式作为 then 回调,所以它不会 "break" 您的链:

dataLayer.loginUser(loginData)
.then(function tryToGetData(response) {
    console.log('loginUser response -> ', response);
    return dataLayer.getData().then(function (response) {
        console.log('loginUser response -> ', response);
        if (response.message === 'JWT_EXPIRED') {
            return tryToGetData(response); // again!
        return response;
    });
}).then(function(response) {
    // next stage
    return …;
});