![](/img/trans.png)
[英]Why cannot assign value inside a function to variable declared outside (globaly)?
[英]I cannot reach to variable declared outside of mongodb function
標題說明了一切我都試過了,但變量只是在 console.log 中返回 undefined
var kategorilerArray;
dbo.collection("anasayfaKategoriler").find().sort(mysort).toArray(function (err, resultKategoriler) {
if (err) throw err;
kategorilerArray = resultKategoriler;
//console.log(kategorilerArray);
});
console.log(kategorilerArray); // > undefined
您記錄 undefined 的原因是因為這就是 JS 的工作方式,這意味着該行代碼將發生在 kategorilerArray 分配之前。 該行將在回調之前運行(toArray function 接收該回調),然后才會發生對 kategorilerArray 的分配。
您可以通過在 toArray 回調 function 或等待 toArray function 中添加 kategorilerArray 分配來修復它,然后進行分配。
這是 JS 事件循環的一部分。
你可以在這篇文章中閱讀更多關於它的信息: https://blog.sessionstack.com/how-javascript-works-event-loop-and-the-rise-of-async-programming-5-ways-to-better-用 2f077c4438b5 編碼
我修好了,只需聲明 express app.post async
var yorumlarArray = await dbo.collection("yorumlar").find().sort(mysort).toArray();
var kategorilerArray = await dbo.collection("anasayfaKategoriler").find().sort(mysort).toArray();
console.log(kategorilerArray);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.