Promise 代表任务的未来结果。在这种情况下,您是fixedItems
在您的任务(对 的调用Item.get
)完成工作之前记录的。换句话说,这些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 摇滚介绍 Promises。