How try to sync,sync instructions with async instructions


  • GNU/Linux

    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


  • Community Rep

    for is synchronous, so you will need to require the async library. That library has an async.each() function which is an asynchronous version of forEach.

    You will want to read up on it here.
    https://github.com/caolan/async#each

    var 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);
    

Log in to reply
 


Looks like your connection to NodeBB was lost, please wait while we try to reconnect.