处理 Bluebird 中的多个嵌套异步操作(承诺)

Handling multiple nested async operations in Bluebird (promises)

我对 JavaScript (Node.js) 和 Promises 还很陌生。我目前正在使用 AWS Lambda 和 DynamoDB。

我有一个从数据库中异步获取的项目列表(已经使用 bluebird promises API 承诺了 AWS SDK。)

对于这些项目中的每一个,我可能需要检索多个子项目(也是异步的),然后对于每个子项目我必须执行另一个异步操作并确定此异步操作是否成功。

对一个项目完成所有异步操作后(即所有子项目的异步操作成功或失败),我需要更新数据库中项目的状态 (fail/success。)

这是我目前所拥有的(下图)。你能告诉我我做的是否正确吗?有没有逻辑错误?可以改进吗?

var doc = require('dynamodb-doc');
var promise = require("bluebird");

var dynamodb = new doc.DynamoDB();

var params = { /* ... */ };

promise.promisifyAll(Object.getPrototypeOf(dynamodb));

dynamodb.queryAsync(params)
    .then(function(data) {
        var items = data.Items;

        var promises = items.map(function(item) {
            params = { /* ...*/ };

            return dynamodb.queryAsync(params)
                .then(function(data2) {
                    var childItems = data2.Items;

                    var morePromises = childItems.map(function(device) {
                        return doAsyncWork()
                            .then(function success() {
                                console.log("Success!");
                            })
                            .catch(function error(err) {
                                console.log("Error!");
                            })
                    });

                    return promise.all(morePromises);
                })
                .then(function() {
                    // Update status for item in DB
                    params = { /* ...*/ };
                    return dynamodb.updateItemAsync(params);
                });
        });

        return promise.all(promises);
    })
    .then(function() {
        var response = { /* ... */ };

        context.succeed(response);
    })
    .catch(function(err) {
        context.fail(err);
    });

一些其他的事情:

为了完成一个项目的所有异步操作,我使用 Promise.all(),并且从文档中我可以看到,即使一个 promise 被拒绝,后续的 promise 也会被拒绝。我不希望这种情况发生,即使一个承诺被拒绝,我也希望它继续。

同样,对于所有项目,我最终都使用 Promise.all() 来等待所有项目完成处理。一个失败了,其他的就不处理了吧?我该如何克服这个问题?

有很多嵌套,我该如何改进这段代码?

我需要一种方法来整合所有结果并将其作为响应传递,例如像这样:

{
    "Results": [{
        "ItemId": " ... ",
        "Status": "Success",
        "ChildItems": [{
            "ChildItemId": " ... ",
            "Status": "Success"
                /*  ...
                ...
                ...
            */
        }]
    }, {
        "ItemId": " ... ",
        "Status": "Error",
        "ChildItems": [{
            "ChildItemId": " ... ",
            "Status": "Success"
        }, {
            "ChildItemId": " ... ",
            "Status": "Error"
        }]
    }]
}

我想到的一个解决方案(可能有点难看)是在外部有一个全局对象,然后将结果存储在其中。还有其他优雅的方法吗?

谢谢。

Can it be improved?

自从您使用 Bluebird 以来,您可以改进一些事情。

使用Bluebird的promise.map()保存代码:

而不是 array.map() 后跟 promise.all(),您可以通过更改代码来使用 Bluebird 的 promise.map()

               var childItems = data2.Items;

                var morePromises = childItems.map(function(device) {
                    return doAsyncWork()
                        .then(function success() {
                            console.log("Success!");
                        })
                        .catch(function error(err) {
                            console.log("Error!");
                        })
                });

                return promise.all(morePromises);

对此:

               return promise.map(data2.Items, function(item) {
                    // do something with item
                    return doAsyncWork();
               });

小心只记录日志的 .catch() 处理程序。

如果您处理一个承诺拒绝并且不重新抛出或return一个被拒绝的承诺,承诺状态将从拒绝变为完成。

因此,当您像此处那样使用 .catch() 时:

        return dynamodb.queryAsync(params)
            .then(function(data2) {
                var childItems = data2.Items;

                var morePromises = childItems.map(function(device) {
                    return doAsyncWork()
                        .then(function success() {
                            console.log("Success!");
                        })
                        .catch(function error(err) {
                            console.log("Error!");
                        })
                });

                return promise.all(morePromises);
            })

这将 "eat" 来自 doAsyncWork() 拒绝承诺的任何错误。有时这就是你想要的(你想处理错误并继续,就好像没有出错一样),但很多时候你需要错误以某种方式传播回来。您可以记录它,但通过重新抛出它让错误传播:

        return dynamodb.queryAsync(params)
            .then(function(data2) {
                var childItems = data2.Items;

                var morePromises = childItems.map(function(device) {
                    return doAsyncWork()
                        .then(function success() {
                            console.log("Success!");
                        })
                        .catch(function error(err) {
                            console.log("doAsyncWork Error: ", err);
                            //rethrow so error propagates
                            throw err;
                        })
                });

                return promise.all(morePromises);
            })

For all async operations of an item to complete I'm using Promise.all(), and from the documentation I can see that if even one promise got rejected the subsequent promises will get rejected as well. I don't want this to happen, I want it to continue even if a single promise is rejected.

在 Bluebird 中,如果您不希望 Promise.all() 在一个承诺被拒绝时中止,您可以使用 Promise.settle() 而不是 Promise.all() 如果您使用的是 Bluebird 2.x。如果您使用的是 Bluebird 3.x,那么当您 return 兑现您的承诺时,您将使用 .reflect()here in the Bluebirds docs 解释了如何执行此操作。就个人而言,我喜欢 Promise.settle() 的工作方式,但一定有一些标准方向的原因需要更改它。

There is a lot of nesting, how may I improve upon this code?

您可以链接您正在做的一些事情而不是嵌套。请参阅 了解在没有太多嵌套和累积结果的情况下对多个操作进行排序的各种方法。