我怎样才能在节点js中为全局变量分配猫鼬结果?

how can i make a assign mongoose result in global variable in node js?

我从数据库中得到了结果(Mongo) 一个函数我根据结果保存了圆顶变量,但是我不能在外部函数中使用那个变量。我怎样才能访问变量?

目前,我在使用 console.but 的函数中得到了一个结果,我在未定义的外部使用了相同的变量,但是,我在未定义的情况下遇到了同样的错误。 没有超时功能怎么完成呢

     var all_mail;
     mailModel.find({}, function (err, docs) {
              console.log(docs); //Got results this console
              all_mail = docs;
               
            });
     console.log(all_mail); //This is showing undefind

您需要了解 node.js 如何处理异步行为。在这种情况下,您的回调函数只能在范围内访问 docs

您的想法是正确的,如果您等待足够长的时间,您的变量很可能会被分配。但是,这确实不是节点的处理方式。

很可能你应该在你传递给 find() 的函数中用 docs 做任何你想做的事。

 mailModel.find({}, function (err, docs) {
   doSomething(docs);
 });

这可能会彻底改变您的程序结构。您可能还想研究使用 promises (http://mongoosejs.com/docs/promises.html) 和 Mongoose,然后使用 async/await,只要您的节点版本支持它。

我相信在 await 中使用 promises 看起来像这样:

var docs = await mailModel.find({}).exec();
doSomething(docs);