L
L
lohmag2016-08-01 19:01:54
JavaScript
lohmag, 2016-08-01 19:01:54

How to bypass js event model?

There was such a question coming from the logic of js, I don’t know how to get around it

var readMacs = function(collection) {
  var macs;
  MongoClient.connect('mongodb://127.0.0.1:27017/snmp', function(err, db) {
    if (err) throw err;
    db.collection(collection).distinct('mac', function(err, docs) {
      console.log(docs);
      db.close();
      return docs;
    })
  });
};
console.log(readMacs('allowedmacs'));

Here's what it returns:
undefined
[ '111a.468a.4985',
  '12aa.468a.4444',
  '14aa.468a.4444',

Those. first comes console.log(readMacs('allowedmacs')) which returns undefined, and then console.log inside the call to the database.
But I need to call this function several times, assign the return value to different variables and then use them inside another function, how can I do this? It is possible to call the following function inside db.collection(collection).distinct('mac', function(err, docs) {}) but I need to call it multiple times and use multiple variables.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
olegshilov, 2016-08-01
@lohmag

Read about promises .

D
de1m, 2016-08-01
@de1m

You can use " async ", great for such things.
You make an array with functions and then this array is fed "asycn.parallel" or "async.serial", depending on whether you want to execute them sequentially or in parallel.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question