2016-11-17 54 views
0

如何訪問回調之外的變量清單? 我想訪問並返回它。nodejs訪問回調方法中的變量

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

//這裏不訪問在上面的回調中, – Joe

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

解決了這個問題,謝謝 – T3rraform

+0

那你能把它標記爲答案嗎? – Joe