NodeJS Async系列不能按顺序工作

时间:2014-08-25 18:21:24

标签: javascript node.js asynchronous npm

我有以下代码,

    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);
        });

我期待这样的输出,

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

但是我得到了以下输出,

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

休息请求输出总是在最后。 这样做的正确方法是什么?

1 个答案:

答案 0 :(得分: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是一个异步函数。通过调用它,你可以将其关闭并继续盲目地继续。将回调移到rest.get的回调函数中。