0

Perhaps my PHP brain does not allow me to do nodejs all I want function "myfindindb" to return a value, is that possible with nodejs? I am aware of async, is this the reason for not working like a waterfall?

var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/exampleDb';
var mysite = '';
var myisfound;
var numItems = '';


function myfindindb(mysite) {

    var findRestaurants = function(db, callback) {

        var cursor = db.collection('restaurants').find({
            "site": mysite
        }).limit(1);

        cursor.each(function(err, doc) {

            assert.equal(err, null);

            var myresults = doc.site;

            return callback(myresults);


        });

       };

    MongoClient.connect(url, function(err, db) {
        assert.equal(null, err);

        findRestaurants(db, function(myresults,callback) {

            console.dir(myresults); //as far as Iv got goo so far

            db.close();

            return callback(myresults); //this bit wont work??
        });


    });

}


var foo = myfindindb('http://google.com');
console.log(foo);
  • You can't directly return a value from an asynchronous operation. The function will return long before the async value is even available. You must use a callback or a promise to communicate the eventually retrieved async value. See all the details and options here: http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – jfriend00 Feb 08 '17 at 17:31
  • Hi thanks for the feedback, searching for "response from an asynchronous call? " never occurred to me. So it seems "await" is the best course of action to use at the moment, I am also looking to to Meteorjs "fibers" – user1426141 Feb 09 '17 at 15:32
  • Keep in mind that you can only `await` something that returns a promise. So, you can either use `await` with the promise or use `.then()` with the returned promise. Either way, you will be returning a promise from your function. – jfriend00 Feb 09 '17 at 17:26

0 Answers0