在 nodejs 中访问外部回调变量,如全局变量 [英] in nodejs access variable outside callback like gloabal varaible

查看:60
本文介绍了在 nodejs 中访问外部回调变量,如全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    var coll= '';
    function test(callback){
        MongoClient.connect(url, function(err, db) {
          if(err) throw err;
          coll=db
          callback(coll);
        });
    }

    test();
    console.log(coll)

这是我的代码.当我打印 'coll' 变量时,它显示未定义.如何从回调外部访问变量.当前获取错误回调不是函数

This is my code. When i print 'coll' variable it says undefined. How to access a variable from the outside of callback. Currently getting error callback is not a function

推荐答案

没有将任何回调函数作为参数传递给您的 test() 函数,因此声明在您的 test() 函数中:callback(coll),将在调用 console.log(coll) 之前抛出一个错误来结束您的脚本.

You are not passing any callback function as argument to your test() function, therefore the statement in your test() function: callback(coll), will throw an error ending your script prior to calling console.log(coll).

这篇关于在 nodejs 中访问外部回调变量,如全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆