Thursday, 28 April 2016

asynchronous - Javascript callback functions returning empty object



I can't seem to get this callback function right.



dispatch: function (query, callback) {

var result = new Object() ;
var qd = new queryDispatcher.init();
var google = qd.callGoogle(query, function(a,b) {
result.gdocs = a ;
result.gtotal = b ;
}) ;

var bing = qd.callBing(query, function(a,b) {
result.bdocs = a ;
result.btotal = b ;

}) ;

var yahoo = qd.callYahoo(query, function(c,d) {
result.ydocs = c ;
result.ytotal = d ;
}) ;

callback(result);
},



As you can see, the query is dispatched and the results are being appended to the results object. However, the callback(result) is still returning an empty object to the parent function which is as follows.



var results = meta.dispatch(query, 
function(result) {
console.log(result);
});
});



Any help will be greatly appreciated!


Answer



Your callback is synchronous, but the properties are asynchronously fetched. When you callback is called, all you got is indeed an empty object.



You should only call the callback after you have all the three answer (use a counter, for example).



dispatch: function(query, callback) {
var result = new Object(),
qd = new queryDispatcher.init(),
counter = 3;


var google = qd.callGoogle(query, function(a,b) {
result.gdocs = a ;
result.gtotal = b ;
checkCallback();
}) ;

var bing = qd.callBing(query, function(a,b) {
result.bdocs = a ;
result.btotal = b ;

checkCallback();
}) ;

var yahoo = qd.callYahoo(query, function(c,d) {
result.ydocs = c ;
result.ytotal = d ;
checkCallback();
});

function checkCallback() {

if (--counter == 0) {
callback(result);
}
}
}


But I'd rather go with promises instead of callbacks. It's a powerful approach.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...