L
L
lohmag2016-08-10 01:17:09
JavaScript
lohmag, 2016-08-10 01:17:09

How to return a Promise from multiple consecutive async calls?

There are three functions, each of which sequentially calls each other and it is necessary to return the result of the work of the last one as a promise, how to do this? Now it doesn't work for me:

var firstfunction = function(docs) {
    MongoClient.connect('mongodb://127.0.0.1:27017/snmp', function(err, db) {
      db.collection('collection).find({}), function(err. docs) {
         secondfunction(docs);
       })
})
}
var secondfunction = function(docs) {
return new Promise(function(resolve) {
MongoClient.connect('mongodb://127.0.0.1:27017/snmp', function(err, db) {
      db.collection('collection).find({}), function(err. docs2) {
        resolve(docs2);
       })
})
})
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry R, 2016-08-18
@dmitrika

db.collection('collection).find({}), function(err. docs2) {

Arguments are separated by commas in JS
And will probably help
return resolve(docs2);

D
denisei, 2016-08-29
@denisei

The mongodb documentation states that if you do not specify a callback in MongoClient.connect, then a Promise is automatically returned to us. Further, collection.find({}) returns a cursor, but if you process the cursor with one of the methods and do not specify a callback, then again you can immediately get a Promise. Armed with this, you can try to do this:

MongoClient.connect('mongodb://127.0.0.1:27017/snmp')
.then(db=>
  db.collection('collection1').find({}).explain()
  .then(explaination=>{
      //делаем что-либо с результатами первого запроса
      //например можно вернуть какие - либо данные:
    return data;
  })
  .then(data=> //если в верхнем then мы вернули некие данные (data) - они передаются сюда
    db.collection('collection2').find({}).explain()
    .then(explaination=>{
        //можно закрыть соединение
        db.close();
        //также делаем что-либо с результатами второго запроса
        //можно скрестить результаты первого запроса (data) и (explaination) и вернуть результат
        return result;
    })
   )
)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question