0

I don't understand, why in the below code glob() internal function don't executes immideately.

'use strict';

const glob = require('glob');

function testFunction(){

    console.log('Checkpoint 1');

    let objectWillBeFilled = {};

    glob(/* GlobPattern */, (errors, files) => {

        console.log('Checkpoint 2');

        files.forEach( (value, index, array) => {

            // do something ...
            // adding some key-value pairs to objectWillBeFilled ...

            console.log('Checkpoint 3');

        });
    });

    console.log('Checkpoint 4');

    return objectWillBeFilled;
}

testFunction();

I get the next sequence of the logs to console:

  1. Checkpoint 1
  2. Checkpoint 4
  3. Checkpoint 2
  4. Checkpoint 3

So, the testFunction returns the empty objectWillBeFilled. What I missed in JavaScript/Node JS learning?

Takeshi Tokugawa YD
  • 670
  • 5
  • 40
  • 124
  • 1
    The concept of asynchronicity, which is kind of the whole point of Node – Ry- Dec 25 '17 at 07:17
  • 1
    return objectWillBeFilled once after the foreach loop is completely executed. You can use async module to use async.forEach and on complete return your result object. Look: https://caolan.github.io/async/docs.html – Aman Gupta Dec 25 '17 at 07:31

0 Answers0