在使用 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);
});
关于javascript - Promise.then 函数内部的外部变量没有被改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33197278/