javascript - Promise.then 函数内部的外部变量没有被改变

标签 javascript node.js promise thinky

在使用 thinky.js 的 Node 上,我试图遍历一个循环并将每个项目添加到一个数组中。但是,由于某种原因,这不起作用。

在另一个地方,它是相同的并且可以工作,只是没有 Promise.then 函数。为什么这不起作用?

var fixedItems = [];
for (i in tradeItems) {
  var item = tradeItems[i];
  Item.get(item["id"]).run().then(function(result) {
    var f = { "assetid": result["asset_id"] };
    console.log(f);  // WOrks
    fixedItems.push(f); // Doesn't work
  });
}

console.log(fixedItems); // Nothing

最佳答案

Promise 表示任务的 future 结果。在这种情况下,您将在任务(对 Item.get 的调用)完成工作之前记录 fixedItems。换句话说,then 函数还没有运行,所以没有任何东西被放入 fixedItems

如果您想在 fixedItems 包含所有项后使用它,则需要等待所有 promise 完成。

具体操作方式取决于您使用的 Promise 库。此示例使用 Promise.all,适用于许多库,包括原生 ES6 Promises:

// Get an array of Promises, one per item to fetch.
// The Item.get calls start running in parallel immediately.
var promises = Object.keys(tradeItems).map(function(key) {
  var tradeItem = tradeItems[key];
  return Item.get(tradeItem.id);
});

// Wait for all of the promises to resolve. When they do,
//  work on all of the resolved values together.
Promise.all(promises)
  .then(function(results) {
    // At this point all of your promises have resolved.
    // results is an array of all of the resolved values.

    // Create your fixed items and return to make them available
    //  to future Promises in this chain
    return results.map(function(result) {
      return { assetid: result.asset_id }
    });
  })
  .then(function(fixedItems) {
    // In this example, all we want to do is log them
    console.log(fixedItems);
  });

推荐阅读:HTML5 rocks intro to Promises .

关于javascript - Promise.then 函数内部的外部变量没有被改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33197278/

相关文章:

javascript - 如何使用 javascript 变量更新 HTML 中的 span 元素?

node.js - 为什么对 Node 服务器的请求挂起?

javascript - 如何让 `dom-if` 重新评估其 `if` 条件?

javascript - Angular 传单图标不会相互替换,而是重叠

node.js - 如何查看loopback内存db中的数据?

javascript - 2个不同的实例保持相同的值

javascript - async wait 返回 Promise 而不是值

javascript - 按顺序排列的多个 jQuery promise

javascript - 如何在 TypeScript 中将函数作为参数传递给 Promise?

javascript - 如何避免下面代码中的 for 循环