【问题标题】:nodejs accessing a variable inside a callback method [duplicate]nodejs在回调方法中访问变量[重复]
【发布时间】:2017-03-31 19:51:18
【问题描述】:

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

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

【问题讨论】:

  • //这里不可访问是在上面的回调中,
  • 你能分享工作代码以便我执行它吗?

标签: javascript node.js variables scope callback


【解决方案1】:

您需要 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);
});

【讨论】:

  • 解决了,谢谢
  • 那你能把它标记为答案吗?
猜你喜欢
  • 1970-01-01
  • 2016-12-15
  • 1970-01-01
  • 2018-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多