本文介绍了如何在mongoose中设置检索回调,在全局变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在全局变量中设置 db
,但是当我得到名称
c> findOne 函数显示我未定义,我该怎么办?
I want to set db
in global variable, but when I get console name
out of findOne
function show me undefined, What can I do?
var name;
schema.findone({name : 'Bob'} , function(er , db){
name = db;
console.log(db);
});
console.log(name);
谢谢。
推荐答案
超级经典初学者对异步的错误:)
Super classic beginner mistake about asynchronism :)
发生了什么:
var name; // FIRST you declare the name variable
schema.findone({name : 'Bob'} , function(er , db){ // SECOND you launch a request to the DB
name = db; // FOURTH name is populated.
console.log(db);
});
console.log(name); // !! THIRD !! you log name - it's empty
你应该做什么:
schema.findone({name : 'Bob'} , function(er , db){
doSomethingElse(db);
});
function doSomethingElse(name){
console.log(name); // It's defined.
}
你甚至不会声明一个全局变量,因为这是一个糟糕的做法。
一旦数据可用,将其传递给另一个函数并执行一些操作。所以你不会污染你的全球范围。
You souldn't even declare a global variable, as it's a bad practice.As soon as the data is available, pass it to another function and do something with it. So you don't pollute your global scope.
编辑:由于某种原因你绝对需要一个全局变量,所以这样做: / p>
Edit : Since you absolutely want a global variable for some reason, then do this :
var name;
schema.findone({name : 'Bob'} , function(er , db){
name = db;
console.log(name); // works fine
doSomethingElse();
});
console.log(name); // name is empty here, because the DB request is still in progress at this stage
function doSomethingElse(){
console.log(name); // Tadaaaa! It's a global variable and is defined!
}
这篇关于如何在mongoose中设置检索回调,在全局变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!