Adrian Florescu Adrian Florescu - 6 months ago 8
Node.js Question

Require module with that executes later on node

In index.js I have a require function and some extra stuff right bellow.

The required module has a delay in execution;

index.js

console.log('1')
var delay_function = require('./delay_function')
console.log('2')


delay_function.js

var fetch = require('node-fetch');

fetch('http://example.com/api').then(function(res){
console.log('wuhu');
});


The result of the two scripts above is:

1
2
wuhu


instead of:

1
wuhu
2


I am new to node and trying to understand how the require function works, but the documentation is so scattered that it's overwhelming.

How can I make the two scripts execute in the order I need them too?

Answer

What you see is perfectly normal.

In your delay_function.js you start a fetch operation in the background, we say the call is non-blocking. It allows node to do other things while the data is begin fetched.

Here is a solution to your problem:

delay_function.js

var fetch = require('node-fetch');
var task = fetch('http://example.com/api');        
task.then(function(res){
    console.log('wuhu');
});

module.exports = task;

index.js

console.log('1')
require('./delay_function').then(function(res) {
  console.log('2')
}

Explaination

The delay_function.js, when required start fetching the result, display wuhu when the fetch is done and returns (using module.exports) the background task, so to say. In the index you retrieve the background task and display 2 when it is done.

Comments