2017-07-24 71 views
0

我是新來的承諾,和我讀一段代碼,這是非常困難的,我明白了:JavaScript和承諾:如何重構/拼合下面的嵌套承諾?

return promise 
    .then(function helper0(instances) { 
     return helper1(instances, options) 
     .then(function helper2() { 
      return bluebird.delay(3000) 
       .then(function helper3() { 
       return helper4(localParams, options); 
       }); 
      } 
     }); 
    }); 

如何重新因素它promise.then().then()...?由於

回答

3

嵌套的承諾是known anti-pattern,你應該把它們連代替:

// the structure is vertical instead of a nested pyramid 
return promise 
    .then(function helper0(instances) { 
    return helper1(instances, options) 
    }) 
    .then(function helper2() { 
    return bluebird.delay(3000); 
    }) 
    .then(function helper3() { 
    return helper4(localParams, options); 
    }); 

返回從傳遞給then回調承諾補充說,承諾鏈條。

使用arrow functions將進一步清理它:

return promise 
    .then(instances => helper1(instances, options)) 
    .then(() => bluebird.delay(3000)) 
    .then(() => helper4(localParams, options); 

但是請注意,使用命名功能將用於調試,因爲一個更可讀的堆棧跟蹤的目的,更好的方法。

+0

謝謝,你有任何建議爲https://stackoverflow.com/questions/45292024/mocha-sinon-unit-tests-for-chained-promise? – BAE

0

假設你的功能也都採用藍鳥的承諾,你可以鏈接你的承諾,而不是嵌套他們是這樣的:

return promise.then(function helper0(instances) { 
    return helper1(instances, options).delay(3000); 
}).then(function helper3() { 
    return helper4(localParams, options); 
}); 

如果helperX()功能並不返回藍鳥許諾,那麼,你可以這樣做:

return promise.then(function helper0(instances) { 
    return helper1(instances, options); 
}).then(function() { 
    return Bluebird.delay(3000); 
}).then(function helper3() { 
    return helper4(localParams, options); 
}); 

當您返回從.then()處理程序中的承諾,即,承諾到鏈條與鏈條等待這一承諾的收益鏈之前完成其餘刀片。這可以讓你像這樣鏈接而不是嵌套一切。

+0

爲什麼downvote?這個答案有什麼問題?第一個代碼塊提供了一個簡單的解決方案,而不是在其他答案中提供的。 – jfriend00

+0

謝謝,你有任何建議爲https://stackoverflow.com/questions/45292024/mocha-sinon-unit-tests-for-chained-promise? – BAE