我只是不知道如何處理“小”問題。可能我在 JavaScript 方面還沒有那么遠,但我現在被困住了......
我想從 MongoDB 中檢索值并根據這些值執行計算。
因為這是異步發生的,所以我必須等到計算完成,然后才能對資料做一些事情。
但是我怎么轉它又轉我不挺身而出,我想不出更多了。我希望有人可以進一步幫助我。我已附上代碼并將控制臺的輸出作為 HTML。
我能想到的唯一可能的方法是先創建資料集,然后進行計算并更新整個事物,但我認為還有更優雅的解決方案。
app.post("/api/insert/recipe", async function (req, res) {
console.log(`/api/test/recipes: create ${req.body.title} `);
let kcal = "0";
console.log("start");
await req.body.ingredients.forEach(async (element) => {
await dbo
.collection("ingredients")
.findOne({
name: element.name,
})
.then((result) => {
kcal = (result.kcal / 100) * element.amount;
console.log("calculate");
});
});
console.log("end");
});
/api/test/recipes: create test
start
end
calculate
uj5u.com熱心網友回復:
forEach不打算與async await.
嘗試將您的代碼更改為:
app.post('/api/insert/recipe', async function (req, res) {
let kcal = 0;
for (const ingredient of req.body.ingredients) {
try {
const ing = await dbo.collection('ingredients').findOne({
name: ingredient.name,
});
kcal = (ing.kcal / 100) * ingredient.amount;
} catch (e) {
console.log(e);
}
}
console.log(kcal);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/513493.html
