运行 在 NodeJS 中同步运行 (MongoDB Operations/Async.js)

Running Functions Synchronously in NodeJS (MongoDB Operations/Async.js)

我正在尝试做一些在 NodeJS 中看起来相当简单的事情 - 我想 运行 函数,一次一个。所有这些函数都有回调。我在下面概述了我的代码,以及它们 运行 的功能以供进一步参考。

我的问题是前两个函数运行得非常好——一次一个,但第三次迭代只是忽略了前两个函数,不管怎样就继续了。这导致了一个真正的问题,因为我的程序将对象放入数据库,并且它导致了重复的对象。

总的目标是让每个函数 运行 一次一个。我在这里缺少什么吗?非常感谢您的帮助!

请注意,在下面的函数中,我已将所有参数简化为 "args" 以便于阅读。

调用函数:

addNewProject(args);
addNewProject(args);
addNewProject(args);

在函数内部,我运行这个:

function addNewProject(args) {
    var info = args;
    queue.push(function (done) {
        loopThroughDetails(info, projID, 0, function () {
            console.log('complete');
            done(null, true);
        });
    });
}

这会调用 loopThroughDetails(),它是与 async.series() 一起工作的集成:

function loopThroughDetails(info, projID, i, callback) {
    if (i < 500) {
        getProjectDetails(projID + "-" + i, function (finished) {
            if (JSON.stringify(finished) == "[]") {
                info.ProjID = projID + "-" + i;
                DB_COLLECTION_NAME.insert(info, function (err, result) {
                    assert.equal(err, null);
                    callback();
                });
            } else {
                i++;
                loopThroughDetails(info, projID, i, callback);
            }
        });

    }
}

调用所有这些后,我只需使用 async.series 即可完成任务:

async.series(queue, function () {
    console.log('all done');
});

我在这里做错了什么?非常感谢您提供的任何帮助! :)

首先,有很多方法可以实现您所寻找的,而且大多数都是主观的。在可能的情况下,我喜欢在同步迭代时使用 array.shift 方法。这个概念是这样的。

// say you have an array of projects you need to add.
var arrayOfProjects = [{name: "project1"}, {name: "project2"}, {name: "project3"}];

// This takes the first project off of the array and assigns it to "next" leaving the remaining items on the array.

var nextProject = function (array) {

    // if there are items left then do work. Otherwise done.
    if (array.length > 0) {
        // shift the item off of the array and onto "next"
        var next = array.shift();

        addNewProject(next);

    }

} 
var addNewProject = function (project) {
    // Do stuff with the project
    console.log("project name: ", project.name);
    // When complete start over
    nextProject(arrayOfProjects);
}

// Start the process
nextProject(arrayOfProjects);

Here is a working Example

如果您检查该页面,您将看到按顺序记录到控制台的项目。