SoFunction
Updated on 2025-03-01

javascript - Solve asynchronous operations of mongoose data query

When I was operating mongoose in a node environment, I found that when I looped the data into an array through nested query, I finally got the array was empty. After several years of Baidu, it still failed. Finally, I asked the masters in the group that it turned out to be caused by mongoose and node asynchronously. Baidu solved the problem. The following is a method I used that I think is relatively simple.

//Original codevar shoppingModel = ('shopping');
var cartsshop = [];
for(var i = 0;i<;i++){
({title:carts[i].title},function (err,shops) {
  if(err){
    return next(err);
  }else{
    (shops);
  }
 });
}
(cartsshop);//[]

By introducing the methods events contained in node itself.

events

All asynchronous I/O operations will send an event to the event queue when completed.

Many objects inside distribute events: an object will distribute an event every time there is a new connection, and an object will emit an event when the file is opened. All these objects that produce events are instances of .

EventEmitter Class

The events module only provides one object: . The core of EventEmitter is the encapsulation of event triggering and event listener functions.
You can access the module by requiring("events");

Here is an example,

// documentvar EventEmitter = require('events').EventEmitter; 
var event = new EventEmitter(); 
('some_event', function() { 
  ('some_event event triggers'); 
}); 
setTimeout(function() { 
  ('some_event'); 
}, 1000); 

Improve my own code as follows:

var shoppingModel = ('shopping');
var cartsshop = [];
var obj ;
var j = 0;
var myEventEmitter = new ();
('next',addResult);
function addResult() {
  (obj);
  j++;
  if(j==){
    (cartsshop);
    (cartsshop);
  }
}
for(var i = 0;i<;i++){
  var ii = i;
 ({title:carts[ii].title},function (err,shops) {
  if(err){
    return next(err);
  }else{
    obj = shops;
    ('next');
  }
 });
}

Of course, it must be introduced before use

var events = require('events');

Finally, the data was successfully retrieved and returned to the client.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.