Hitu Bansal
Hitu Bansal

Reputation: 3137

Function Calling Execution in nodejs

I have this code.

for(var i = 0; i< bookmarks.length; i++){
        (function(i) {
            parseArticle(i,bookmark_id,bookmark_url,function(err,result){
                console.log("Success");
            });

        })(i);

}   


function parseArticle(i,bookmark_id,bookmark_url,callback) {
            diffbot.article({uri: url}, function(err, response) {
                console.log("Diffbot is" );
            });
            console.log("Parse Article" );
    callback(null,i);
};

Now output is coming like this

Parse Article

Sucess

Diffbot is

I want to execute function in this way so output will be like

Diffbot

Parse Article

Sucess

Can anybody tell me what is exact problem here and how to resolve that

Thanks

Upvotes: 0

Views: 42

Answers (2)

jfriend00
jfriend00

Reputation: 708206

You need to learn what an asynchronous function and its completion callback are. When you understand that, you will understand why "Parse Article" is printed first and will have a better idea how you should structure your code. In a nutshell, an asynchronous functions starts an operation (which usually involves timers or networking or I/O of some kind) and the rest of your code continues to execute. Then, some time LATER, the asynchronous operation completes and the completion callback is called.

The key to using an asynchronous operation is that ALL activity that you want to happen after the asynchronous operation and all activity that you want to use the result of the asynchronous activity MUST be inside the callback that indicates the completion of the async activity.

In your particular case, you can achieve the desired output by putting things into the diffbot.article callback. This should generate this log:

Diffbot
Parse Article
Sucess

function parseArticle(i,bookmark_id,bookmark_url,callback) {
      diffbot.article({uri: url}, function(err, response) {
            // put everything in here that should occur after the async
            // operation is done
            console.log("Diffbot is" );
            console.log("Parse Article" );
            callback(null,i);
      });
};

Upvotes: 1

majidarif
majidarif

Reputation: 20105

You should do some research into asynchronous programming with callbacks.

for(var i = 0; i< bookmarks.length; i++){
  parseArticle(i,bookmark_id,bookmark_url,function(err,result){
    console.log("Success");
  });
}   

function parseArticle(i,bookmark_id,bookmark_url,callback) {
  diffbot.article({uri: url}, function(err, response) {
    console.log("Diffbot is");
    console.log("Parse Article");
    callback(null, i); // this will call the success
  });
}

try reading this.

Upvotes: 0

Related Questions