Javascript Node.js和数据库变量中的回调

Javascript Node.js和数据库变量中的回调,javascript,node.js,Javascript,Node.js,我不理解nodejs中的回调 我需要从数据库中获取一个播客号码,并在代码中使用它 我现在从console.log获取 [Function: index] node.js中是否有任何解决方案可以从数据库中获取变量并在以后的代码中重用它 var index = function( callback ) { var podcast = 0; User.findOne({ sessionID: this.event.session.sessionId }, function(

我不理解nodejs中的回调

我需要从数据库中获取一个播客号码,并在代码中使用它

我现在从console.log获取

[Function: index]
node.js中是否有任何解决方案可以从数据库中获取变量并在以后的代码中重用它

var index = function( callback ) {   
    var podcast = 0;  
    User.findOne({ sessionID: this.event.session.sessionId }, function(err, user) {
          if (err ||!user){

          }
          else {
             console.log(user);
             podcast = user.podcast;
          }
        });
    callback( podcast );
};

index();

var callback = function(data) {
    return data;
}

var iUseMyAnywhere = callback;

PS.编辑以跟随问题

想象一下,你到了一家餐馆,坐下来请一位女服务员喝杯咖啡。但与此同时,你并没有冻僵,你在移动、做事、说话,所以一旦你的咖啡准备好了,服务员就会把它拿给你,你就会停止你正在做的其他事情,喝你的咖啡

所以,它会变成这样:

    User.findOne({ sessionID: this.event.session.sessionId }).exec().then(data => {
    console.log(data);
}).catch(err => {
    console.log(err);
});

看起来我不可能在Node.js中完成我想做的事情

这完全有可能。只是,您需要使用异步API,这使它更加安全

node.js中是否有任何解决方案可以从数据库中获取变量并在以后的代码中重用它

var index = function( callback ) {   
    var podcast = 0;  
    User.findOne({ sessionID: this.event.session.sessionId }, function(err, user) {
          if (err ||!user){

          }
          else {
             console.log(user);
             podcast = user.podcast;
          }
        });
    callback( podcast );
};

index();

var callback = function(data) {
    return data;
}

var iUseMyAnywhere = callback;
不完全是。当您连接到数据库时,或者,顺便说一句,异步执行任何操作,例如通过http获取内容或从光盘读取内容时,您不能将该内容直接分配给:

var myUserFromDb = User.find('john doe', function(err, res){...}); //this will fail 
因为作为第二个参数传递的函数将在将来某个时候执行
User.find()

因此,遗憾的是,您不能在
user
var中获取用户并将其传递给另一个模块,比如说播客模块

但是,假设您有一个“user.js”模块,它公开了一个
withUser
方法,然后为一个用户访问数据库,然后在db调用得到解决时与用户一起调用提供的函数

假设您有一个“podcast.js”文件/模块,其中包含一个需要用户的
getPodcast
方法

getPodcast
不能只问“user.js”一个用户。但是,它可以要求使用作为参数传递的用户运行的函数:

User.js

function withUser(callback){
    User.find({_id: 1}, (err, user)=> {
        callback(user);
    })
}
function getPodcast(){

    withUser( function(user){
        //now we really have the user inside podcast.js, and we can work with it.
        //Sadly, that will surely involve more asynchronous api's, which is painful.
    })
}
function getUser(id){
    //let's say we return a promise that wraps the `User.find` database request
}
getUser(userId).then(user => getPodcast(user)).then(podcastResult => ...)
 async function getPodcast(userId){
      const user = await User.getUser(uesrId);
      const otherAsyncThing = await ...someAsyncApiCall;

      doAnythingWithUser(user); //this line won't execute until user is resolved, even if there aren't callbacks involved :-D
 }
podcast.js

function withUser(callback){
    User.find({_id: 1}, (err, user)=> {
        callback(user);
    })
}
function getPodcast(){

    withUser( function(user){
        //now we really have the user inside podcast.js, and we can work with it.
        //Sadly, that will surely involve more asynchronous api's, which is painful.
    })
}
function getUser(id){
    //let's say we return a promise that wraps the `User.find` database request
}
getUser(userId).then(user => getPodcast(user)).then(podcastResult => ...)
 async function getPodcast(userId){
      const user = await User.getUser(uesrId);
      const otherAsyncThing = await ...someAsyncApiCall;

      doAnythingWithUser(user); //this line won't execute until user is resolved, even if there aren't callbacks involved :-D
 }
现在,
getPodcast
将可以在其参数回调中访问用户

有没有比回调更简单的方法

是的,你应该。当使用承诺时,事情会——稍微少一点——痛苦。promise api的作用如下:

User.js

function withUser(callback){
    User.find({_id: 1}, (err, user)=> {
        callback(user);
    })
}
function getPodcast(){

    withUser( function(user){
        //now we really have the user inside podcast.js, and we can work with it.
        //Sadly, that will surely involve more asynchronous api's, which is painful.
    })
}
function getUser(id){
    //let's say we return a promise that wraps the `User.find` database request
}
getUser(userId).then(user => getPodcast(user)).then(podcastResult => ...)
 async function getPodcast(userId){
      const user = await User.getUser(uesrId);
      const otherAsyncThing = await ...someAsyncApiCall;

      doAnythingWithUser(user); //this line won't execute until user is resolved, even if there aren't callbacks involved :-D
 }
podcast.js

function withUser(callback){
    User.find({_id: 1}, (err, user)=> {
        callback(user);
    })
}
function getPodcast(){

    withUser( function(user){
        //now we really have the user inside podcast.js, and we can work with it.
        //Sadly, that will surely involve more asynchronous api's, which is painful.
    })
}
function getUser(id){
    //let's say we return a promise that wraps the `User.find` database request
}
getUser(userId).then(user => getPodcast(user)).then(podcastResult => ...)
 async function getPodcast(userId){
      const user = await User.getUser(uesrId);
      const otherAsyncThing = await ...someAsyncApiCall;

      doAnythingWithUser(user); //this line won't execute until user is resolved, even if there aren't callbacks involved :-D
 }
这看起来并不是更好。但是,当您使用promise api时,就可以开始使用

podcast.js

function withUser(callback){
    User.find({_id: 1}, (err, user)=> {
        callback(user);
    })
}
function getPodcast(){

    withUser( function(user){
        //now we really have the user inside podcast.js, and we can work with it.
        //Sadly, that will surely involve more asynchronous api's, which is painful.
    })
}
function getUser(id){
    //let's say we return a promise that wraps the `User.find` database request
}
getUser(userId).then(user => getPodcast(user)).then(podcastResult => ...)
 async function getPodcast(userId){
      const user = await User.getUser(uesrId);
      const otherAsyncThing = await ...someAsyncApiCall;

      doAnythingWithUser(user); //this line won't execute until user is resolved, even if there aren't callbacks involved :-D
 }

最后一条未经询问的建议:在使用node.js时,在编写大量代码之前,请确保您了解回调api和异步的工作原理。否则,您将得到真正耦合且脆弱的代码,其中对象通过大量回调,代码无法读取且无法调试:-D

@dm03514。谢谢,我要求您不要立即关闭它。你为自己感到骄傲吗?
开心吗?@AnnaK简短的回答是否定的。回调在未来某个时刻运行,你无法预测,因此在它的块中发生的事情只在该块中可用。如果您想让行为更像您习惯的那样,您需要在最新的节点版本中使用Promissions以及新的async/await功能。@Paul thank:)您能推荐我一些链接吗?我的案例很难实施吗?看起来我无法回答,但这是文档。看起来我不可能在Node.js中做什么:(什么是路由器?它是一个nodejs模块吗?作为一个优秀的JS开发人员,你能告诉我什么是解决我问题的最佳方法吗?我只想从数据库中获取数据并将其放入另一个变量,该变量稍后在我的代码中使用。谢谢你的帮助,但我仍然无法解决我的问题:(我又哭了。你需要创建另一个名为callback的函数来使用代码中其他地方的数据。请参阅我的编辑。Andy,但我不想将此变量放入控制台,我希望将其传递给另一个变量,例如podcast。我希望在其他地方使用podcast作为数据库中的值。我更新了我的问题。你是我的今日英雄:)您所要做的就是在需要使用数据时使用return。将callback分配给一个变量,如示例中所示。但从外观上看,在掌握其他关键概念之前,您需要先了解编码的其他方面。对于许多人来说,这是一件痛苦的事情,这就是人们称之为callback的原因回叫地狱。我个人讨厌它。我用可观察物来处理它们,有时还用承诺。但是