简体   繁体   中英

NodeJS Variable outside function scope

For the life of me I cannot work this one out. Have look around and tried many many different ways of trying to get this to go. Currently have the following code.

var config = require("./config.js");                                                            
var cradle = require('cradle')                                                          
var MikroNode = require('mikronode');                                                   
var WebServer = require('./bin/www');                                                   
var Routers = "Hasnt changed";

var conndb = new(cradle.Connection)(config.couchdb.host);
var db = conndb.database(config.couchdb.db);

db.exists(function(err, exists){
  if (err) { console.log('error', err);}
  else if (exists) { console.log('Seems the Force is with you - Database Exists');}
  else { db.create(); }
});

db.temporaryView({
  map: function (doc){
    if (doc.type=='ConfigRouter') emit(doc.name, doc);
    }
    }, function (err, res){
        Routers = JSON.stringify(res);
    }
);

console.log(Routers);

As it stands it will respond with:

E:\Dev\MM>npm start

> MM@0.0.1 start E:\Dev\MM
> node ./Start.js

Hasnt changed
Seems the Force is with you - Database Exists

I am assuming it is an asynchronous call to the CouchDB and is not filling the result in time before it displays the result. How do I get around this issue?

You are right, the call is asynchronous so when console.log(Routers); is processed, Routers is "Hasnt changed". One way of doing it would be to use promises thanks to the Q npm module:

var Q = require('q');

var deferred = Q.defer();
db.temporaryView({
  map: function (doc) {
    if (doc.type=='ConfigRouter') emit(doc.name, doc);
  }
}, function (err, res) {
  deferred.resolve(JSON.stringify(res));
});

deferred.promise
  .then(function (data) {
    Routers = data;
    console.log(Routers);
    // do some stuff...
  })
  .done();

Maybe it's possible to do something better without using Q.defer and adapting directly the callback: https://github.com/kriskowal/q#adapting-node

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM