在嵌套函数中使用set变量global cant

时间:2018-01-28 17:04:34

标签: javascript node.js nedb

我使用nodejsnedb作为数据库。

我使用名称(结果)定义一个变量并将其设置在嵌套函数中,但它仍未定义



let result
function userExist(chatId) {
    db.find({'chatId': chatId}, function (err, docs) {
        result = docs.length
        console.log(result) // returns a number
    })

    console.log(result) // returns undefined
}




1 个答案:

答案 0 :(得分:0)

这可能是因为您在调用console.log之后和传入的回调之前立即调用了第二个db.find,这会将值分配给result。如果您注意到消息在控制台中的显示顺序,您可以自己解决这个问题。

相关问题