Answer the question
In order to leave comments, you need to log in
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
db.collection('collection).find({}), function(err. docs2) {
return resolve(docs2);
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 questionAsk a Question
731 491 924 answers to any question