Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/grails/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 回调函数外部的变量为空_Node.js_Callback_Return_Nosql - Fatal编程技术网

Node.js 回调函数外部的变量为空

Node.js 回调函数外部的变量为空,node.js,callback,return,nosql,Node.js,Callback,Return,Nosql,我是一个nodej初学者,实际上我尝试使用NoSQL数据库构建一个简单的登录via。摘要身份验证。我还创建了一个名为“users”的模块,它加载到我的应用程序中 现在,当我尝试调用回调函数中的数据结果时,我得到了正确的数据。在同一个回调中,我将返回的数据分配给变量记录。当我在外部调用变量时,我将得到空的结果-错误在哪里 var dbdriver = require('nosql'), dbfile = dbdriver.load("./db.nosql"), records = null db

我是一个nodej初学者,实际上我尝试使用NoSQL数据库构建一个简单的登录via。摘要身份验证。我还创建了一个名为“users”的模块,它加载到我的应用程序中

现在,当我尝试调用回调函数中的数据结果时,我得到了正确的数据。在同一个回调中,我将返回的数据分配给变量记录。当我在外部调用变量时,我将得到空的结果-错误在哪里

var dbdriver = require('nosql'),
dbfile = dbdriver.load("./db.nosql"),
records = null

dbfile.top(1000).callback(function(err, response) {
    (function(users) {
        records = users
        console.log(users) // Here i get the wanted result
    })(response)
})

console.log(records) // Here the result is empty

非常感谢:)

由于您在回调中调用的是console.log(用户),因此正确反映了该值。这是javascript中异步调用的一种行为。因此,最后一行console.log(records)可能会在回调执行之前首先运行,因此到目前为止的记录没有任何值。 因此,我建议您将函数设为对用户执行某些操作的函数,并在回调中调用它

var dbdriver = require('nosql'),
dbfile = dbdriver.load("./db.nosql"),
records = null

dbfile.top(1000).callback(function(err, response) {
    (function(users) {
        //records = users
        //console.log(users) // Here i get the wanted result
        doSomethingToUsers(users); 
    })(response)
})

function doSomethingToUsers(users) {
 // do something to users
}

//console.log(records) // Here the result is empty

我觉得这是个时间问题。在调用(异步)回调函数之前调用外部作用域中的
console.log(records)
时,
records
正好包含最初分配的值(
records=null

只有在调用异步回调后,才会设置
records
变量

这有用吗