Javascript 在NodeJS中同步运行函数(MongoDB Operations/Async.js)
我试图做一些在NodeJS中看起来相当简单的事情——我想一次运行一个函数。所有这些函数都有回调。我在下面概述了我的代码,以及它们运行的函数,以供进一步参考 我的问题是,前两个函数工作得非常好——一次一个,但是第三次迭代忽略了前两个函数,不管怎样都会继续。这导致了一个真正的问题,因为我的程序将对象放入数据库,这导致了重复的对象 总体目标是让每个函数一次运行一个。这里有我遗漏的东西吗?非常感谢你的帮助 请注意,在下面的函数中,为了便于阅读,我将所有参数简化为“args” 调用函数:Javascript 在NodeJS中同步运行函数(MongoDB Operations/Async.js),javascript,node.js,mongodb,asynchronous,async.js,Javascript,Node.js,Mongodb,Asynchronous,Async.js,我试图做一些在NodeJS中看起来相当简单的事情——我想一次运行一个函数。所有这些函数都有回调。我在下面概述了我的代码,以及它们运行的函数,以供进一步参考 我的问题是,前两个函数工作得非常好——一次一个,但是第三次迭代忽略了前两个函数,不管怎样都会继续。这导致了一个真正的问题,因为我的程序将对象放入数据库,这导致了重复的对象 总体目标是让每个函数一次运行一个。这里有我遗漏的东西吗?非常感谢你的帮助 请注意,在下面的函数中,为了便于阅读,我将所有参数简化为“args” 调用函数: addNewPr
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()一起工作的集成:
我做错了什么?非常感谢您提供的任何帮助!:) 首先,有很多方法可以实现你想要的,而且大多数都是主观的。如果可能,我喜欢在同步迭代时使用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);
如果您查看该页面,您将看到按顺序记录到控制台的项目。是否有这样显式调用addNewProject方法的原因?它们可以通过循环等迭代过程一次调用一个吗。。。例如,如果您只有一两个项目要添加,该怎么办?非常感谢您的帮助!这个简单的解释让我的一周都很开心!!:)已经摆弄了五天了。不知道为什么有人否决了这个完美的答案:(不客气!有些人只是自恋,不关心别人。这里的目标是在何时何地为你提供帮助。你可能不会总能得到语法上最正确的答案,但有时一个简单的概念会有所帮助。似乎人们已经期望你成为专家了。同意!我想人们情绪低落并不重要现在就投票吧,因为答案已经在这里了:)
async.series(queue, function () {
console.log('all done');
});
// 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);