Reputation: 839
I have the following method:
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);
});
};
I want to call this method twice and combine their results. I have implemented it using callbacks in a following way:
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);
});
});
Is there any better way to make it synchronous? I read about a few things (promises and sync-client), but I didn't understand. What is the best way to call that function twice and combine their results?
Upvotes: 1
Views: 68
Reputation: 6958
First of all, it doesn't look like your code is synchronous. I would suggest to leave it asynchronous and use promise library like Q. First, make sure Q is installed:
npm install q
From your get
function, return a promise:
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;
};
From your code that calls the get function:
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);
});
Upvotes: 2