To make a parallel "request" in Mongoose

I am new to Mongoose, so please carry me.

Is there a way to execute two queries in "parallel". Or at least request two documents and return their results together? Callback designation disables me a bit during synchronization.

In pseudo code, this is what I am looking for:

function someWork(callback) { var task1 = service.doQueryAndReturnTask(); var task2 = service.doQueryAndReturnTask(); waitAll(task1, task2); callback(task1, task2); } 

I know this is not a solution, due to the need to have a doQueryAndReturnTask callback, but I need a template that works, and referrable does not bind callbacks

+4
source share
2 answers

This is not about Mongoose. Node.js is an asynchronous language, so it allows you to simultaneously perform any number of asynchronous tasks (for example, database queries).

What you need is some lib to handle the asynchronous control flow, like async.js or when.js :

 var when = require('when'); var someWork = function(callback) { when.all([ collection1.find(query1).exec(), collection2.find(query2).exec() ]).spread(callback) .otherwise(function(err) { // something went wrong }); }; 

when.js is a module for processing promises. So, if you don't need promises, you can use async.js :

 var async = require('async'); var someWork = function(callback) { async.parallel([ function(cb) { collection1.find(query1, cb) }, function(cb) { collection2.find(query2, cb) } ], function(err, res) { if (!err) return callback.apply(null, data); // something went wrong }); }; 

Update: Promises is an alternative way to handle an asynchronous control flow by transferring asynchronous functions using promises.

Usually, in order to get the results of an asynchronous function, you must pass it a callback that will be executed somewhere in the future.

When you use promises, instead of passing some callback, you immediately get a promise of the execution results that will be resolved somewhere in the future.

So, Promises allows you to work with asynchronous functions synchronously, using Promises instead of real data. Promises also allows you to wait for results at any time.

In my example, I execute two queries, getting two Promises for their results. Then I suggest that node wait until both Promises are executed, passing their results to the callback function.

Here you can read promises/A+ here . You can also see when.js api docs .

+11
source

Currently, this can be achieved using Promise.all :

 Promise.all([ collection1.find({foo: 'bar'}), collection2.find({fooey: 'bazzy'}) ]).then(([fooResults, fooeyResults]) => { console.log('results: ', fooResults, fooeyResults); }).catch((err) => { console.log('Error: ', err); }); 
0
source

Source: https://habr.com/ru/post/1490653/


All Articles