在node.js中同步调用

时间:2014-12-22 16:11:19

标签: node.js asynchronous

我有以下方法:

var get = function(query_para,callback) {

    var queryParams = query_para;
    var timestamp ;
    var some_Data = {};
    var data;

    request({url:"http://some-url.com/q?", qs:queryParams}, function(err, response, body) {
        if(err) { console.log(err); return; }
        console.log(body);
        var data = JSON.parse(body);

        some_Data.count = data.count; 

        console.log("Returned data: "+some_Data.count);

         callback(null,some_Data);
    });

};

我想两次调用此方法并结合其结果。我使用回调以下列方式实现了它:

get({ start: '2014/09/13-10:00:00', end: '2014/09/13-11:00:00', format: 'json' }, function(err, result1){
    get({ start: '2014/09/13-11:00:00', end: '2014/09/13-12:00:00', format: 'json' }, function(err, result2){
        console.log("r1:: "+result1.count);
        console.log("r2:: "+result2.count);
    });
});

有没有更好的方法让它同步?我读了几件事(promises和sync-client),但我不明白。两次调用该函数并结合其结果的最佳方法是什么?

1 个答案:

答案 0 :(得分:2)

首先,它看起来不像你的代码是同步的。我建议让它保持异步并使用像Q这样的promise库。首先,确保安装了Q:

npm install q

从您的get函数中返回一个承诺:

var get = function(query_para) {

    var queryParams = query_para;
    var timestamp ;
    var some_Data = {};
    var data;
    //Use q
    var Q = require("q");

    //define a deferred that will be resolved later
    var deferred = Q.defer();

    request({url:"http://some-url.com/q?", qs:queryParams}, function(err, response, body) {
        if(err) { console.log(err); return; }
        console.log(body);
        var data = JSON.parse(body);

        some_Data.count = data.count; 

        console.log("Returned data: "+some_Data.count);

        //resolve the deferred here
        deferred.resolve(some_Data);
    });

    //return the promise
    return deferred.promise;
};

从调用get函数的代码中:

var q = require("q");
var promiseArr = [];
//First promise to your get function
promiseArr.push(get({ start: '2014/09/13-10:00:00', end: '2014/09/13-11:00:00', format: 'json'}));
//Second promise
promiseArr.push(get({ start: '2014/09/13-11:00:00', end: '2014/09/13-12:00:00', format: 'json' }));

//Use q.all to call a callback when all promises in the array are resolved:
q.all(promiseArr).then(function (results) {
   //First item is the data resolved from the first promise in the array
   console.log("r1:: "+results[0].count);
   //Second item is data resolved from second promise
   console.log("r2:: "+results[1].count);
});