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

    test();
    console.log(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

AJS
  • 953
  • 7
  • 21
  • coll=db; try this – Mahi Nov 08 '16 at 08:10
  • 1
    already done that inside MongoClient.connect function . – AJS Nov 08 '16 at 08:14
  • the callback is asynchronous you put `console.log(coll);` inside a callback function. you can not call the variable `coll` outside the function because it will only be defined after the `MongoClient.connect` callback since it is asynchronous. thats why `console.log(coll)` outputs empty|undefined|null – Beginner Nov 08 '16 at 08:58

1 Answers1

1

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).

Rax Weber
  • 3,730
  • 19
  • 30
  • 1
    should it be like test(function(coll) { console.log(coll) } ) – AJS Nov 08 '16 at 08:17
  • @ABC It depends. What do you want to do with the callback function? – Rax Weber Nov 08 '16 at 08:18
  • i want to make coll variable global . so that i can access database object outside MongoClient.connect function . how can we do this ? Please help – AJS Nov 08 '16 at 08:21
  • Just try first removing the callback. Let me know about the results. – Rax Weber Nov 08 '16 at 08:23
  • 1
    thanks it worked like this var coll= ''; function test(callback){ MongoClient.connect(url, function(err, db) { if(err) throw err; callback(db); }); } test(function(result){ coll = result; }); console.log(coll) but coll is undefined outside test() . can't we access it like global variable outside callback ? – AJS Nov 08 '16 at 09:12