I'm very new to programming (3 months) and am having trouble with how node handles asynchronous functions (I think).
I have a Merchant class object with a method "addMenu" that makes a GET request for a menu from an external API and then updates the merchant by setting the merchant.data.menu object (which is null by default) to the new menu we just got.
Code in question:
this.addMenu = function(currentMerchant) {
var id = currentMerchant.id;
function getMenu(id) {
var deferred = Q.defer();
var url = 'https://api.delivery.com/merchant/'+id+'/menu?client_id=xyz';
request.get(url, function(error, response, body) {
if(error) {
console.log("Something went wrong with menu GET request: Status Code: " + response.statusCode);
deferred.reject(new Error(error));
} else if(!error && response.statusCode == 200) {
menuObj = JSON.parse(body);
deferred.resolve(menuObj);
}
});
return deferred.promise;
};
this.data.menu = getMenu(id).then(function(currentMenu) {
return currentMenu;
});
console.log(this.data.menu);
};
When I log (this.data.menu), I get "{ state: 'pending' }." I can do setTimeout and get things to work but doesn't that defeat the whole purpose of promises? I've been stuck on this general problem for days - have been delving into callbacks, delays, promises etc to solve it but am thinking I might be missing something more fundamental in my thinking.
Thank you!
Edit to add:
Well after all that I realized that the real crux of my problem was the inability to access this.data.menu from inside of the callback / promise which lead me to doing all kinds of weird stuff and trying to return them into the this. variable etc.
Just read up on the "var that = this;" trick to gain access to class scope which made all of my callback and promise attempts work fine and make sooo much more sense in my head. And I now know a hell of a lot more about promises that I ever intended as a side benefit. Thanks for the help folks!