蓝鸟的嵌套承诺

Jef*_*eff 7 javascript promise bluebird

我正在试图找出如何正确使用蓝鸟库的promises.我在我的代码中遇到了一些嵌套的promise,我注意到在bluebird文档中它的内容如下:

如果您正在使用完整的bluebird API产品,那么您几乎不需要首先采用嵌套承诺.

关于承诺被滥用的许多其他博客文章和嵌套是一种常规的反模式.

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)
                });
        }
    });
Run Code Online (Sandbox Code Playgroud)

我的所有函数都返回对象.看看蓝鸟文档,似乎有多种帮助方法:all(),join(),props().

所以,我的问题是:如果存在依赖关系,我怎么能避免嵌套?也许这是我对承诺的异步性质的误解.这样的事可以吗?

Promise.all(loadCar(someUri), loadMake(car.make), loadModel(make.model))
    .then(function(car, make, model) {
        // do logic
    });
Run Code Online (Sandbox Code Playgroud)

Ber*_*rgi 6

您总是需要为控制结构嵌套,并且通常需要一级嵌套来传递给函数表达式then().这不是完全可以避免的,但可以大大减少.

在您的情况下,您甚至可以省略一些函数表达式并直接传递函数.

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)
Run Code Online (Sandbox Code Playgroud)