0

I have the below code,

    var async = require('async'); var rest = require('restler');

    async.series([
        function(callback){
           rest.get('https://api.twitter.com/1.1/statuses/mentions_timeline.json').on('complete', function(result) {
              if (result instanceof Error) {
                console.log('Error:', result);
                this.retry(5000); // try again after 5 sec
              } else {
                console.log(result);
              }         });
            callback(null, 'one');
        },
        function(callback){
            console.log('2nd function');
            callback(null, 'two');
        }
        ],

// optional callback
        function(err, results){
               // results is now equal to ['one', 'two']
               console.log(results);
        });

I am expecting output like this,

{ errors: [ { message: 'Bad Authentication data', code: 215 } ] }
2nd function
[ 'one', 'two' ]

But am getting the below output,

2nd function
[ 'one', 'two' ]
{ errors: [ { message: 'Bad Authentication data', code: 215 } ] }

Rest request output always coming at last. What is the correct way of doing this?

1 Answer 1

1
    function(callback){
       rest.get('https://api.twitter.com/1.1/statuses/mentions_timeline.json').on('complete', function(result) {
          if (result instanceof Error) {
            console.log('Error:', result);
            this.retry(5000); // try again after 5 sec
          } else {
            console.log(result);
             callback(null, 'one');
          }
       });
    },

rest.get is an asynchronous function. By calling it, you fire it off and continue blindly. Move your callback into rest.get's callback function.

Sign up to request clarification or add additional context in comments.

4 Comments

Excellent, I didn't think this way, is there way I can identify which are asynchronous calls and which are synchronous calls?
Generally, if the call requires a callback function, then it is asynchronous.
There are very few synchronous calls in node and they are usuaully xxxSync() method name. The area where you use the sync methods is in the file system module.
Yeah, I think I should understand the concepts in a better way. Thanks for the information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.