How try to sync,sync instructions with async instructions
-
My problem is some method to sync sync instruction with async instruction. This is an example(in library.js):
// I have an Object with some propriety var index; for(index in array){ db.getObject(------,function(err,returnData){ //in this method modify string in some way console.log("METHOD"); }); } console.log(" STRING ");
When I look the console.log I see that the print "STRING" is not at the end of all prints "METHOD" but it is over the last print. I think is a async problem. Anyone can help me?
I
-
for
is synchronous, so you will need to require theasync
library. That library has an async.each() function which is an asynchronous version offorEach
.You will want to read up on it here.
https://github.com/caolan/async#eachvar async = require.main.require('async'); function doLast(){ console.log(" STRING "); } var array = [a, b, c]; async.each(array, function(value, next){ // The value is sent here, not the index, if you really need the index, you can use forEachOf() or do array.indexOf(value). db.getObject(------,function(err,returnData){ //in this method modify string in some way console.log("METHOD"); // Call next() to let the the app know that the async operation is complete. next(); }); // When all async operations are complete, run doLast. }, doLast);
Copyright © 2024 NodeBB | Contributors