T3rraform T3rraform - 17 days ago 5
Javascript Question

nodejs accessing a variable inside a callback method

How can I access the variable inventory outside the callback?
I would like to access it and return it.

loadInventory = function () {

var inventory = [];

offers.loadMyInventory({
appId: 730,
contextId: 2,
tradableOnly: true

}, function (err, items) {
items.forEach(function (item) {
inventory.push({
asset_id: item.id,
market_name: item.market_name
});
});
//Not accessible here
});
};

Joe Joe
Answer

You need loadInventory to take a callback, that whatever calls it would pass:

loadInventory = function (callback) {

var inventory = [];

offers.loadMyInventory({
    appId: 730,
    contextId: 2,
    tradableOnly: true

}, function (err, items) {
    items.forEach(function (item) {
        inventory.push({
            asset_id: item.id,
            market_name: item.market_name
        });
    });
    callback(inventory);
});
}; 

loadInventory(function(inventory) {
  console.log(inventory);
});
Comments