Monday, 22 May 2017

Issue with Javascript foreach Async behavior

After a bit of research online, it seems like Javascirpt's forEach loop IS blocking but my following code is proving otherwise:

I am using node js mongoDB driver to get docs from my collection which is an array (named documents)

 collectionInstance.find({}, function(err, documents) {
      if (err || !documents) {
        console.log('no documents found in the collection');
      } else {

        console.log('before');

        documents.forEach(function(document) {
          console.log('inside')
        });

        console.log('outside');


      }
    });

What I want:

before -> inside, inside, inside .... inside -> outside

What it's giving me:

before -> after -> inside, inside, inside .... inside 

Why is the loop behaving as if it's non blocking?



via nitinsh99

No comments:

Post a Comment