重写这个科学怪人的承诺链

Rewriting this frankenstein promise chain

所以我把这个可憎的东西带到了生活中,我无法在我的生活中思考如何以这样的方式优化它我可以 运行 这个链正确使用 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;
        }
      });

},

[编辑] 澄清一下,我使用的是 bluebird

一个好的 promise 库(不确定你使用的是哪个)的一些功能是你可以像这样链接 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
});

希望这能提供信息。

稍作重构并更改代码风格即可。

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);
    )
  )
},