nodejs访问回调方法

时间:2016-11-17 10:11:32

标签: javascript node.js variables scope callback

如何在回调之外访问变量库存? 我想访问它并将其返回。

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
});
};

1 个答案:

答案 0 :(得分:0)

你需要loadInventory来进行回调,无论它传递什么样的调用:

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);
});