【问题标题】:Running Functions Synchronously in NodeJS (MongoDB Operations/Async.js)在 NodeJS 中同步运行函数 (MongoDB Operations/Async.js)
【发布时间】:2017-03-25 01:34:38
【问题描述】:

我正在尝试做一些在 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');
});

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

【问题讨论】:

  • 您是否有理由像这样显式调用 addNewProject 方法?是否可以通过循环等迭代过程一次调用一个?例如,如果您只有一两个项目要添加怎么办?

标签: javascript node.js mongodb asynchronous async.js


【解决方案1】:

首先,有很多方法可以实现您的目标,而且大多数都是主观的。如果可能,我喜欢在同步迭代时使用 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

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

【讨论】:

  • 非常感谢您的帮助!这个简单的解释让我度过了一周! :) 一直在摆弄这个五天。不知道为什么有人反对这个非常好的答案:(
  • 不客气!有些人只是自恋,不关心别人。这里的目标是在您可以的时间和地点提供帮助。您可能并不总是得到语法上最正确的答案,但有时一个简单的概念会有所帮助。似乎人们已经期望你成为专家了。
  • 同意!我想人们现在投反对票并不重要,因为答案已经在这里了:)
猜你喜欢
  • 2016-03-06
  • 2020-06-23
  • 2022-08-19
  • 2015-08-15
  • 2012-12-03
  • 2017-12-20
  • 1970-01-01
  • 2018-01-09
  • 2019-10-11
相关资源
最近更新 更多