[英]Outer variables not being altered inside Promise.then function
在使用thinky.js的節點上,我試圖遍歷循環並將每個項添加到數組中。 然而,由於某種原因,這是行不通的。
在另一個地方,只是沒有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
承諾代表任務的未來結果 。 在這種情況下,您在任務(對Item.get
的調用)完成工作之前記錄fixedItems
。 換句話說, then
函數還沒有運行,因此沒有任何東西放入fixedItems
。
如果你想使用fixedItems
一旦它包含所有項目,你將需要等待所有的promises解決。
你如何做到這取決於你正在使用的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 。
您的問題是您在循環中的任何promise完成執行之前調用console.log(fixedItems)
。 另一種解決異步問題的更好方法是首先將所有項ID放在數組中並檢索單個查詢中的所有項,這在數據庫端也更有效。
var itemIds = tradeItems.map(function(item) {
return item.id;
});
var fixedItems = [];
//you would need to write your own getItemsById() function or put the code
//to get the items here
getItemsById(itemIds).then(function(items) {
items.forEach(function(item) {
var f = { "assetid": result["asset_id"] };
fixedItems.push(f);
});
whenDone();
});
function whenDone() {
//you should be able to access fixedItems here
}
我無法輕易找到如何在一個查詢中使用thinky查找多個ID記錄,但我確實找到了這個可能有用的頁面: http : //c2journal.com/2013/01/17/rethinkdb-filtering-for -multiple的IDS /
雖然這是我解決此問題的首選方法,但在繼續使用后續代碼之前,仍然可以使用多個查詢並使用promise鏈等待所有問題得到解決。 如果你想走那條路,請看看這個鏈接: http : //promise-nuggets.github.io/articles/11-doing-things-in-parallel.html 。 (注意:我沒有親自使用Bluebird,但我認為該鏈接中的Bluebird示例可能已過時。 map
方法似乎是當前推薦的使用promises執行此操作的方法: https : //stackoverflow.com/ a / 28167340/560114 。)
更新:或者對於后一個選項,您可以使用上面的joews答案中的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.