【问题标题】:How to make this code execute in an appropriate order如何使此代码以适当的顺序执行
【发布时间】:2016-02-08 22:14:55
【问题描述】:

我正在使用 mongodb 在 node.js 中编写一个 Web 应用程序。我有这段代码,但不幸的是它没有按顺序执行,我的意思是 for 循环的迭代速度比那些 db 函数的执行速度要快,这不会造成混乱。

hospitalsCollection.update({}, {$pull: {doctors: parseInt(id)}}, function(err, success) {
    treatmentsCollection.update({}, {$pull: {doctors: parseInt(id)}}, function(err, success) {
        hospitalsCollection.find({"_id": {$in: hospitalsIds}}).toArray(function(err, hospitalsList) {
            for(i = 0; i < hospitalsList.length; i++) {
                for(j = 0; j < hospitalsList[i].treatments.length; j++) {
                    var exists = false;
                    for(k = 0; k < hospitalsList[i].doctors.length; k++) {
                        doctorsCollection.find({"_id": parseInt(hospitalsList[i].doctors[k])}).toArray(function(err, doctorObj) {
                            for(l = 0 ; l < doctorObj.treatments.length; l++) {
                                if(doctorObj.treatments[l] == hospitalsList[i].treatments[j]) {
                                    exists = true;
                                    break;
                                }
                            }
                        });
                        if(exists)
                            break;
                    }
                    if(exists) {
                        break;
                    }
                    else {
                        hospitalsCollection.update({"_id": parseInt(hospitalsList[i]._id)}, {$pull: {treatments: parseInt(hospitalsList[i].treatments[j])}}, function(err, success) {
                            treatmentsCollection.update({"_id": parseInt(hospitalsList[i].teratments[j])}, {$pull: {hospitals: parseInt(hospitalsList[i]._id)}}, function(err, success) {
                                console.log(err);
                            });
                        });
                    }
                }
            }

            for(i = 0; i < treatments.length; i++) {
                doctorsCollection.aggregate([ {$project:{"treatments._id":1, "treatments.price":1}}, {$unwind:"$treatments"},{$match:{"treatments._id": parseInt(treatments[i])}}, {$sort:{"treatments.price":-1}}, {$limit:1} ], function(err, result) {
                    doctorsCollection.aggregate([ {$project:{"treatments._id":1, "treatments.price":1}}, {$unwind:"$treatments"},{$match:{"treatments._id": parseInt(treatments[i])}}, {$sort:{"treatments.price":1}}, {$limit:1} ], function(err, result2) {
                        var maxPrice = result[0].treatments.price;
                        var minPrice = result2[0].treatments.price;
                        treatmentsCollection.update({"_id": parseInt(treatments[i])}, {$set: {"maxPrice": parseInt(maxPrice)}}, function(err, success) {
                            treatmentsCollection.update({"_id": parseInt(treatments[i])}, {$set: {"minPrice": parseInt(minPrice)}}, function(err, success) {
                                console.log(err);
                            });
                        });
                    });
                });
            }
        });
    });
});

我真的不知道该如何处理。任何帮助将不胜感激。谢谢。

【问题讨论】:

    标签: node.js loops for-loop asynchronous


    【解决方案1】:

    使用 Promise(bluebird 很棒)。并重构你的代码。

    使用 Promise,您可以执行以下操作。

    dbUpdate1()
    .then(function(resultFromUpdate1) {
    
        let multipleUpdates = []
        multipleUpdates.push(updateCollectionA())
        multipleUpdates.push(updateCollectionB())
    
        return Promise.all(multipleUpdates)
    
    .spread(afterUpdatingBothCollection)
    
    
    function updateCollectionA(argument) {
        // body...
    }
    
    function updateCollectionB(argument) {
        // body...
    }
    
    function afterUpdatingBothCollection(resultFrom1, resultFrom2) {
        // body...
    }
    

    【讨论】:

    • 我不确定如何在我的情况下使用它;/
    • @kuba12 Promise 允许您同步编写代码。 doThis() 然后 doThat()。我更新了上面的答案以使其更清晰
    • 好的,但我说的是那些 for 循环。我不知道如何确保在使用 'k'(第 7 行)甚至 'j'(第 5 行)迭代的 for 循环之前执行第 8-15 行。
    • @kuba12 你可以将它们移动到它自己的函数中。
    猜你喜欢
    • 1970-01-01
    • 2018-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 2012-04-21
    • 1970-01-01
    相关资源
    最近更新 更多