2016-01-20 25 views
0

所以我把這種可憎的東西帶到生活中,我無法爲我的生活得到我的頭如何優化它,我可以使用Promise.all/Promise.join正確運行此鏈。重寫這個frankenstein諾言鏈

任何人都能指出我正確的方向嗎?應該首先分開這些方法。

任何洞察力是讚賞。

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

 
},

[編輯]爲了澄清,我使用藍鳥

+0

這是否實際工作?你永遠不應該能夠返回承諾的結果。你只能退還承諾本身。 – slebetman

+0

我似乎得到了我的結果就好了 –

+0

您是否意味着在'spread'回調函數中返回'client.setAsync(...') – acbabis

回答

2

重構一下,並更改代碼樣式給出了這一點。

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

+0

所以其他的t如果這個if/else,在清潔方面代碼是'好的'?主要關注(ab)錯誤地使用Promises。 –

+2

@KevinToet其實,if/else也是一個偏好問題。你沒有濫用Promises,IMO。當你不需要時,承諾濫用就是嵌套大量的回調。 – acbabis

+0

什麼是您使用的lambda註釋? Eclipse正在嘗試着。你能否解釋get(1)? –

1

一個很好的承諾庫的一些特性(不知道哪一個您正在使用),就是你可以鏈承諾像這樣:

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

希望這是提供信息。