重写这个弗兰肯斯坦承诺链

Rewriting this frankenstein promise chain

本文关键字:承诺 弗兰肯斯坦 重写      更新时间:2023-09-26

所以我把这个可憎的东西带到了生命中,我一生都无法弄清楚如何优化它,这样我就可以使用 Promise.all/Promise.join 正确运行这条链。

有人能为我指出正确的方向吗?应该先分开方法。

任何见解都值得赞赏。

getOpenIDConf: function() {
  return client
    .getAsync('openId')
    .then(
      function(result) {
        if (!result) {
          return request
            .getAsync({
              url: 'https://accounts.google.com/.well-known/openid-configuration',
              json: true
            }).spread(
              function(response, body) {
                var result = JSON
                  .stringify(body);
                client.setAsync('openId',
                  result).then(
                  function() {
                    return result;
                  });
              });
        } else {
          return result;
        }
      });
},

[编辑] 澄清一下,我正在使用蓝鸟

稍微

重构一下并更改代码样式就可以做到这一点。

getOpenIDConf: () => client.getAsync('openId').then(result =>
    result || request.getAsync({
      url: 'https://accounts.google.com/.well-known/openid-configuration',
      json: true
    }).get(1).then(JSON.stringify).then(result =>
      client.setAsync('openId', result).return(result);
    )
  )
},

一个好的 promise 库(不确定你使用的是哪个库)的一些功能是你可以像这样链接承诺:

doSomething(function(result) {
  return doSomethingElse();
}).then(function(result2) {
  return doSomethingElseAgain();
}).then(function(result3) {
  // It all worked!
}).catch(function() {
  // Something went wrong
});

或者,您可以等待一组完成:

var promiseArray = [];
promiseArray.push(doSomething());
promiseArray.push(doSomethingElse());
promiseArray.push(doSomethingElseAgain());
Promise.all(promiseArray).then(function() {
  // It all worked!
}).catch(function() {
  // Something went wrong
});

希望这是有益的。