我想告诉您,访问数据库和检索数据等此类操作是异步操作,因此它们的工作方式不同,您不能像基本同步操作那样只分配值。事实上这就是 Node.js 的要点。如果您点击链接,您可以阅读更多内容:https://nodejs.org/about/ https://nodejs.org/about/
那么如何解决您所面临的问题。我可以为你提供2种方式:
回调
这实际上就是您此时所使用的。您需要运行基本函数并放置另一个(回调)函数作为附加参数,因此一旦一切准备就绪,回调函数将被触发,您将能够获得结果。如何将结果接收到变量中:
var searchQuery = {}; //or something specific like {name: 'Kitten Name'};
var foundKittens = [];
Kitten.find(searchQuery , function (err, kittens) {
if (err) {
//do something with error
} else {
foundKittens = kittens
}
});
请注意,由于这些异步操作的特定性,您必须在现有回调内继续执行所有其余操作。很快你就会面临“回调地狱”的问题。
有关回调和“回调地狱”的更多信息,您可以在那里阅读:
http://callbackhell.com/ http://callbackhell.com/
Promises
这是使用异步函数的更容易理解和更专业的方式。 Mongoose ODM 支持承诺 (http://mongoosejs.com/docs/api.html#promise_Promise http://mongoosejs.com/docs/api.html#promise_Promise),因此您可以执行以下操作。
var searchQuery = {}; //or something specific like {name: 'Kitten Name'};
var foundKittens = [];
Kitten
.find(searchQuery)
.exec()
.then(function(kittens){
//here you can assign result value to your variable
//but this action is useless as you are working with results directly
foundKittens = kittens;
return kittens;
})
.onReject(function(err){
throw err; //or something else
});
因此,您只需在现有的承诺范围内工作,您可能会有越来越多的“然后”语句,例如:
Kitten
.find(searchQuery)
.exec()
.then(function(kittens){
foundKittens = kittens;
return kittens;
})
.then(countKittents)
.then(changeSomethingInKittents)
.then(saveKittentsToDb)
.onReject(function(err){
throw err; //or something else
});
有关承诺的更多信息,请阅读:
http://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html http://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html