This question already has an answer here:
这个问题在这里已有答案:
- How do I return the response from an asynchronous call? 30 answers
- 如何从异步调用返回响应? 30个答案
I'm trying to put data into an object. Although this object in loop has value, this object out of the loop hasn't value (empty). I had instance object global variable obj
. What's wrong with me?
我正在尝试将数据放入对象中。尽管循环中的此对象具有值,但此循环外的对象没有值(空)。我有实例对象全局变量obj。我怎么了?
p.s : findOne is a mongoose's method. (mongodb).
p.s:findOne是一种猫鼬的方法。 (MongoDB的)。
var obj = [];
for(var i = 0;i<anotherObj.length;i++){
var id = anotherObj[i].id;
model.findOne({_id:id},function(err,user){
if(!err){
obj.push(user);
console.log(obj); /* <= it has value */
}
})
}
console.log(obj); /* <= this is null */
2 个解决方案
#1
1
Your findOne callback runs asynchronous, meaning that your last console.log runs before you push the user to the obj (array).
您的findOne回调运行异步,这意味着在将用户推送到obj(数组)之前,您的上一个console.log运行。
You would need to call a function after every user in the loop has been fetched. Try the async package
在获取循环中的每个用户之后,您需要调用一个函数。尝试使用异步包
#2
1
Your query to mongoose are asynchronous. The callbacks will be executed only on the next iteration of the event loop/when the data is available. That is why you see the obj being null.
您对mongoose的查询是异步的。回调将仅在事件循环的下一次迭代/数据可用时执行。这就是为什么你看到obj为null的原因。
#1
1
Your findOne callback runs asynchronous, meaning that your last console.log runs before you push the user to the obj (array).
您的findOne回调运行异步,这意味着在将用户推送到obj(数组)之前,您的上一个console.log运行。
You would need to call a function after every user in the loop has been fetched. Try the async package
在获取循环中的每个用户之后,您需要调用一个函数。尝试使用异步包
#2
1
Your query to mongoose are asynchronous. The callbacks will be executed only on the next iteration of the event loop/when the data is available. That is why you see the obj being null.
您对mongoose的查询是异步的。回调将仅在事件循环的下一次迭代/数据可用时执行。这就是为什么你看到obj为null的原因。