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


i'm trying simple seems in nodejs - want run functions, 1 @ time. of these functions have callbacks. have outlined code below, function run further reference.

my problem first 2 working absolutely fine - 1 @ time, third iteration ignores first 2 functions , goes anyway. causing real problem, since program works putting objects database, , it's causing duplicate objects.

the overall goal have each function run 1 @ time. there i'm missing here? help!

please note in functions below, have simplified parameters "args" easier reading.

calling functions:

addnewproject(args); addnewproject(args); addnewproject(args); 

inside functions, run this:

function addnewproject(args) {     var info = args;     queue.push(function (done) {         loopthroughdetails(info, projid, 0, function () {             console.log('complete');             done(null, true);         });     }); } 

this calls loopthroughdetails(), integration work 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);             }         });      } } 

and after calling this, use async.series accomplish task:

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

what doing wrong here? can give! :)

firstly, there many methods achieve looking , subjective. use array.shift method when iterating synchronously when possible. concept goes this.

// have array of projects need add. var arrayofprojects = [{name: "project1"}, {name: "project2"}, {name: "project3"}];  // takes first project off of array , assigns "next" leaving remaining items on array.  var nextproject = function (array) {      // if there items left work. otherwise done.     if (array.length > 0) {         // shift item off of array , onto "next"         var next = array.shift();          addnewproject(next);      }  }  var addnewproject = function (project) {     // stuff project     console.log("project name: ", project.name);     // when complete start on     nextproject(arrayofprojects); }  // start process nextproject(arrayofprojects); 

here working example

if inspect page see projects logged console in order.


Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -