0

I want to handle nodejs asynchronous issue. please help me with a sweet example - it ll be better for me if you able to do it by callback or like callback related thing.

Thanks

Rohan Kumar
  • 5,427
  • 8
  • 25
  • 40
Milan Mahata
  • 599
  • 1
  • 6
  • 12
  • 1
    Didn't you find anything on the internet? – Rohan Kumar Sep 20 '17 at 09:54
  • I unable to find out the the proper one ..can you help me out please? i am new in node js – Milan Mahata Sep 20 '17 at 09:56
  • Yes we can help you, but it's not quite clear what are you trying to ask. Please elaborate further whether you're talking about `forEach` method in javascript or callbacks in general – Rohan Kumar Sep 20 '17 at 10:00
  • i am using a foreach -> and inside the foreach doing lots of functions , do i want to do when forech one round execution totaly complete than it ll move to next round ...need an eaxple – Milan Mahata Sep 20 '17 at 10:07
  • Read [this](https://stackoverflow.com/questions/9329446) and see if it helps. It has got some examples of `forEach` – Rohan Kumar Sep 20 '17 at 10:16
  • oppps! i know foreach i want help on synchronous foreach ...https://www.npmjs.com/package/sync-each take a look i unable to implement it . – Milan Mahata Sep 20 '17 at 10:19

1 Answers1

0

Sample examples

Foreach loop

var fs = require('fs')
var paths = ['/home' , '/root', '/var']
paths.forEach(function( path ) {
  fs.lstat( path, function(err, stat) {
    console.log( path, stat );
  });
});

For loop

for (var i = 0, c = paths.length; i < c; i++)
{
  // creating an Immiedately Invoked Function Expression
  (function( path ) {
    fs.lstat(path, function (error, stat) {
      console.log(path, stat);
    });
  })( paths[i] );
  // passing paths[i] in as "path" in the closure
}

Recursion

    function iteratePath(paths, i, max){
      if(i<max) {
       return;
      }else{
          fs.lstat( path, function(err, stat) {
            console.log( path, stat );
            //Recursive call back
            iteratePath(paths, i, max)
          });
        }
    }

var paths = ['/home' , '/root', '/var']
iteratePath(paths,0, size)

You can use async Using async/await with a forEach loop

Devaraj C
  • 317
  • 3
  • 11
  • thanks for the example Devaraj , are you sure about ..var fs = require('fs') var paths = ['/home' , '/root', '/var'] paths.forEach(function( path ) { fs.lstat( path, function(err, stat) { console.log( path, stat ); }); }); – Milan Mahata Sep 20 '17 at 10:33