CrazySynthax
CrazySynthax

Reputation: 15008

node.js: how to return a value of a callback function?

I have the following code (that doesn't work as expected):

var express = require('express')
var app = express()
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/interviews';

app.get('/', function(req, res){
    var result = get_document(res);
    res.send( result // show the results of get document in the browser //)
    console.log("end");
});

app.listen(3000, function(req, res) {
    console.log("Listening on port 3000");
});

function get_document() {
  MongoClient.connect(url, function(err, db) {
    var col = db.collection('myinterviews');
    var data = col.find().toArray(function(err, docs) {
      db.close();
      return docs[0].name.toString(); // returns to the function that calls the callback
    });
  });
}

The function 'get_document' is supposed to return the documents stored in 'myinterviews' collection. The problem is that the line 'return docs[0]...' returns to col.find (which is the function that called the callback) and not to variable 'result' inside app.get(...).

Do you know how to make the documents return to 'result' variable?

Upvotes: 0

Views: 5549

Answers (2)

Dave Cooper
Dave Cooper

Reputation: 10714

Your get_document function runs asynchronously. The call to MongoClient.connect() could take some time, so it can't return immediately. To return the value you're after from your database call, you'll have to pass a callback into the get_document function. So it should look something like this:

var express = require('express')
var app = express()
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/interviews';

app.get('/', function(req, res){
    var result = get_document(function(result) {
        res.send(result);
        console.log("end");
    });
});

app.listen(3000, function(req, res) {
    console.log("Listening on port 3000");
});

function get_document(done) {
  MongoClient.connect(url, function(err, db) {
    var col = db.collection('myinterviews');
    var data = col.find().toArray(function(err, docs) {
      db.close();
      done(docs[0].name.toString()); // returns to the function that calls the callback
    });
  });
}

Upvotes: 1

Alex
Alex

Reputation: 11

You should have a look at the promise api.

the "get_document" function should return a new promise, with resolve and reject function callbacks (success/failure).

So, it should look a bit like this:

var express = require('express')
var app = express()
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/interviews';

app.get('/', function(req, res){
var result = get_document(res).then(function (doc) {
  res.send( doc);
});
 // show the results of get document in the browser //)
console.log("end");
});

app.listen(3000, function(req, res) {
    console.log("Listening on port 3000");
});

function get_document() {

  return new Promise(

     function (resolve, reject)
       MongoClient.connect(url, function(err, db) {
       var col = db.collection('myinterviews');
       var data = col.find().toArray(function(err, docs) {
        db.close();
        resolve(docs[0].name.toString()); // returns to the function that calls the callback
    });
  });
  );
}

Upvotes: 1

Related Questions