When I am operating in the node environment mongoose, found that I through the nested form of query to the data loop into an array, the end of the array has been empty, after Baidu, still no fruit, finally asked the group of the Great God, the original is mongoose and node asynchronous caused , Baidu to solve the solution, the following is my use of a method I think is relatively simple.
Varshoppingmodel = Global.dbHandle.getModel (' shopping ');
for (Vari = 0;i<carts.length;i++) {
Shoppingmodel.findone ({title:carts[i].title},function (err,shops) {
Console.log (Cartsshop);//[]
|
Through the introduction of node itself contains methods events.
Events
Node.js all asynchronous I/O operations will send an event to the event queue when they are completed.
Many objects in Node.js distribute events: A Net.server object distributes an event each time a new connection is made, and a Fs.readstream object emits an event when the file is opened. All of the objects that generate the event are events. An instance of Eventemitter.
Eventemitter class
The events module provides only one object: events. Eventemitter. The core of Eventemitter is the encapsulation of event triggering and event listener functions.
You can access the module by require ("events").
Here's an example,
Event.js file
Vareventemitter = require (' Events '). Eventemitter;
Varevent =neweventemitter ();
Event.on (' Some_event ', function () {
Console.log (' some_event event Trigger ');
});
settimeout (function () {
Event.emit (' some_event ');
}, 1000);
|
Make improvements to my own code, as follows:
Varshoppingmodel = Global.dbHandle.getModel (' shopping ');
Varmyeventemitter =newevents. Eventemitter ();
Myeventemitter.on (' Next ', Addresult);
for (Vari = 0;i<carts.length;i++) {
Shoppingmodel.findone ({title:carts[ii].title},function (err,shops) {
Myeventemitter.emit (' Next ');
|
Of course, use must be introduced before
Varevents = require (' events ');
|
Finally, the data is successfully removed and returned to the client.