Adrian Florescu
Adrian Florescu

Reputation: 4492

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?

Upvotes: 0

Views: 74

Answers (2)

Tuan Anh Tran
Tuan Anh Tran

Reputation: 7237

Javascript is non blocking so when you require, it doesn't block the execution and display 2 right away. when fetch finish, it display wuhu.

To do that in order, you can use Promise.

Basically it will look like this

doThis().then(doThat)

Upvotes: 1

DARK_DUCK
DARK_DUCK

Reputation: 1777

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.

Upvotes: 1

Related Questions