蓝鸟的嵌套承诺 [英] nested promises in bluebird

查看:101
本文介绍了蓝鸟的嵌套承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to figure out how to use promises correctly with the bluebird library. I've come across some nested promises in my code and I noticed that in the bluebird docs it reads:


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

if you are utilizing the full bluebird API offering, you will almost never need to resort to nesting promises in the first place.

还有很多关于承诺滥用的博客文章,嵌套是一种常规的反模式。

There are many other blog posts about promises being misused and nesting is a regular anti-pattern.

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()。

All of my functions return objects. Looking at the bluebird docs, it seems like there are multiple helper methods: all(), join(), props().

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

So, my question is: How could I avoid the nesting if there are dependencies? Perhaps this is my misunderstanding of the asynchronous nature of promises. Could something like this work?

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


推荐答案

你总是需要为控制结构嵌套,通常你传递给 then()的函数表达式需要一级嵌套。这不是完全可以避免的,但可以显着减少

You always need nesting for control structures, and usually you will need one level of nesting for the function expressions passed to then(). It's not totally avoidable, but can be reduced significantly.

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

In your case, you even can omit some of the function expressions and pass the functions directly.

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)

这篇关于蓝鸟的嵌套承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆