再见,我不想拐弯抹角,我想我的问题很简单。 我有一个函数来得到一个交易的总成本。 有一个forEach(用于用户想要购买的每件商品)。 这是我现在所掌握的:
async function getTotalCost(ListOfItems) {
return new Promise ((resolve, reject) => {
var totalcost = 0;
ListOfItems.forEach( async (market_hash_name, index) => {
var cost = await Price.findOne({ market_hash_name: market_hash_name });
if (cost == null) {return reject("item cost not found")}
cost = cost.price
console.log("DEBUG - cost:",market_hash_name,cost)
totalcost = totalcost + cost
if (index === ListOfItems.length -1) {
console.log('DEBUG - totalcost:',totalcost)
resolve(totalcost)
}
});
})
}
我在stack overflow上搜索有类似问题的人,结果发现:Best way to wait for.foreach()to complete。 正如你可能知道的那样,我接受了所提出的解决方案。 然而我发现它只是耽误了问题,这里有一个日志:
DEBUG - cost: Sealed Graffiti | Keep the Change (Battle Green) 3
DEBUG - cost: Sealed Graffiti | Eco (Frog Green) 3
DEBUG - cost: Sealed Graffiti | Sorry (Desert Amber) 3
DEBUG - cost: Sealed Graffiti | QQ (Cash Green) 3
DEBUG - totalcost: 12
STEAM BOT - item being sent to user
STEAM BOT - pending
DEBUG - cost: Sealed Graffiti | Speechless (Violent Violet) 3
DEBUG - cost: Sealed Graffiti | Toasted (Tiger Orange) 3
DEBUG - totalcost: 6
DEBUG - cost: Sealed Graffiti | Backstab (Shark White) 3
DEBUG - cost: Sealed Graffiti | Keep the Change (Frog Green) 3
有什么建议吗? 我可能会用一些很愚蠢的方法来解决这个问题,但我更喜欢一个更有效的解决方案,而不是我可能会积攒的东西。
foreach
不支持承诺。 它不能支持异步
和等待
。 不能在foreach
中使用await
。
为了等待结果,我们应该回到老派的“for循环”,但是这次您可以使用现代版本的for.。of构造(多亏了迭代协议)来提高可读性:
async function processArray() {
for (const item of array) {
await delayedLog(item);
}
}
并行处理数组
async function processArrayInPArallel() {
const promises = array.map(delayedLog);
await Promise.all(promises);
}