我正在试图弄清楚如何正确使用蓝鸟库的promises.我在代码中遇到了一些嵌套的promise,我注意到在bluebird文档中它的内容如下:
if you are utilizing the full bluebird API offering,you will almost never need to resort to nesting promises in the first place.
关于承诺被滥用的许多其他博客文章和嵌套是一种常规的反模式.
loadCar(someUri) // jqXHR
.then(function (car) {
if (carHasFourDoors(car)) {
loadMake(car.make)
.then(function (make) {
loadModel(make.model)
.then(function (model) {
loadCarDetails(model)
});
});
}
else if (carHasTwodoors(car)) {
loadModel(make.model)
.then(function (model) {
loadCarDetails(model)
});
}
});
我的所有函数都返回对象.看看蓝鸟文档,似乎有多种辅助方法:all(),join(),props().
所以,我的问题是:如果存在依赖关系,我怎么能避免嵌套?也许这是我对承诺的异步性质的误解.可以这样的工作吗?
Promise.all(loadCar(someUri),loadMake(car.make),loadModel(make.model))
.then(function(car,make,model) {
// do logic
});
解决方法
您总是需要为控制结构进行嵌套,并且通常需要对传递给then()的函数表达式进行一级嵌套.这不是完全可以避免的,但可以是
reduced significantly.
在您的情况下,您甚至可以省略一些函数表达式并直接传递函数.
loadCar(someUri).then(function (car) {
if (carHasFourDoors(car)) {
return loadMake(car.make)
else if (carHasTwodoors(car))
return make; // not sure actually where you get this from
}).then(function (make) {
return loadModel(make.model)
}).then(loadCarDetails)