0

I am looking to return a value to a varible when I call the function in nodejs.
The output I am looking for is "Calling From Glasgow to Euston"
The output I am getting is "Calling From undefined to undefined"

Code is the following.

function trainstation(stx, callBack) {
  MongoClient.connect(ttdb, function(err, db) {
  if (err) throw err;
   var dbo = db.db("ttdb");
   var collection = dbo.collection("tlc");
   var find = collection.find( { "Stanox" : stx } );
   find.toArray(function(err, result) {
     if (err) throw err;
    db.close();
    return callBack(result);        
   });
 });
};

function gettrain(){
   var ts1 = trainstation(9531, function(x){
     return x[0]['Station Name'];
   });
   var ts2 = trainstation(31033, function(x){
   return x[0]['Station Name'];
   });
   console.log("Calling From", ts1, "to", ts2);
  };
gettrain();

Thanks :)

5
  • Than why aren't you just doing it like this: trainstation(9531, function(x){ ts1 = x[0]['Station Name']; }); Commented Feb 15, 2020 at 19:32
  • Which version of the MongoDB driver is this? Newer versions support promises and you should consider using them rather than callbacks because it will make your life better. Commented Feb 15, 2020 at 19:34
  • using ts1 = inside the function yields the same results. Commented Feb 15, 2020 at 19:37
  • @jarmod version is 3.5.2 Commented Feb 15, 2020 at 19:38
  • The problem you have right now is that the final console.log() happens before either of the callbacks happen, hence ts1 and ts2 are undefined. You can confirm this by adding console.log() statements into the callback handlers. This is basic async JavaScript behavior. BTW that version of MongoDB package does support modern async JavaScript (see mongodb.github.io/node-mongodb-native/3.2/reference/…). Commented Feb 15, 2020 at 19:46

1 Answer 1

3

I don't use the MongoDB package and I don't have MongoDB up & running right now to test this, so I've written this code purely based on a quick read of the reference documentation. Perhaps you can test this and we'll fix any minor issues. Copy this code to a new source file and test it.

What I've done is to take advantage of the MongoDB package's promise features. You can see that the code is more linear and simpler to follow.

const MongoClient = require('mongodb').MongoClient;
const ttdb = 'mongodb://localhost:27017'; // or your DB URL

const trainstation = async (Stanox) => {
  const client = MongoClient(ttdb);
  await client.connect();
  const dbo = client.db("ttdb");
  const collection = dbo.collection("tlc");
  const result = await collection.find({Stanox}).toArray();
  client.close();
  return result;       
};

const gettrain = async () => {
  const ts1 = await trainstation(9531);
  const ts2 = await trainstation(31033);
  const sn1 = ts1[0]['Station Name'];
  const sn2 = ts2[0]['Station Name'];
  console.log("Calling From", sn1, "to", sn2);
};

gettrain();
Sign up to request clarification or add additional context in comments.

4 Comments

Okays so witth some Tweaks I manged to get promsie pending as a result. code //Find Train Station Name const trainstation = async (stx) => { const client = MongoClient(ttdb); await client.connect(); const dbo = client.db("ttdb"); const collection = dbo.collection("tlc"); const result = await collection.find( { "Stanox" : stx} ).toArray(); client.close(); return result; }; ts1 = trainstation(9531); console.log(ts1); code @jarmod
Couple of minor changes added. Might have to fire up MongoDB if we're not close.
you legend, the () on the ts1 / ts2 did the trick. Thanks so much really appriciate it
Here's a helpful blog post that compares the same solution using callbacks, promises, and async/await: stackify.com/async-javascript-approaches. There are also good videos on YouTube (search for 'js callback promises async'), for example youtube.com/watch?v=gB-OmN1egV8.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.