How try to sync,sync instructions with async instructions

NodeBB Plugins
  • GNU/Linux
    #1

    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
    #2

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

Suggested Topics


  • 0 Votes
    7 Posts
    405 Views

  • 1 Votes
    5 Posts
    1335 Views

  • 0 Votes
    2 Posts
    872 Views

  • 0 Votes
    6 Posts
    1972 Views

  • 3 Votes
    5 Posts
    2160 Views

| | | |