简体   繁体   中英

Foreach loop with mongoDB call / node.js

  result.forEach(element => {
    //Get each element
    console.log("LOOP");
    dbo.collection("users").findOne({email: emailGiven, "friends.email": element.email},function(errT, resultT) {
      if (errT){
        console.log("Query Error Inside!");
        res.status(errT.status); // or use err.statusCode instead 
        console.log(errT);
        //db.close();
        //return res.send(errT.message);
      }
      else {
        if (resultT) {
          var oneUser = {
            email: element.email,
            username: element.username,
            fullName: element.fullName,
            status: resultT
          };
          //console.log(resultT);
          foundUsers.push(oneUser);
        } else {
          //Not found means not added or pending
          var oneUser = {
            email: element.email,
            username: element.username,
            fullName: element.fullName,
            status: 0
          };
          foundUsers.push(oneUser);
          //console.log(emailGiven +  " " + element.email)
          console.log(oneUser);                  
        }
      }
    });
  });

i have an object array for each elemant i would like to do mongoDB call for each element and depending on the results i wanna push the results in an array as im doing, the problem is that mongoDb is async so my main thread finished before i can push results to the array foundUsers, how may i fix this issue?

As you said, need to do handle an asynchronous operation into a synchronous loop. For doing this, you can use async library. It is so useful in such operatinos.

Just install async module in your project first npm install --save async

Afterwards, you can do sth like this:

// for use with Node-style callbacks...
var async = require("async");

var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"};
var configs = {};

async.forEachOf(obj, (value, key, callback) => {
    fs.readFile(__dirname + value, "utf8", (err, data) => {
        if (err) return callback(err);
        try {
            configs[key] = JSON.parse(data);
        } catch (e) {
            return callback(e);
        }
        callback();
    });
}, err => {
    if (err) console.error(err.message);
    // configs is now a map of JSON data
    doSomethingWith(configs);
});

For working with this library, it uses async.forEachOf function instead of simple forEach loop. Three parameters is sent to this function.

  1. The 1st parameter that is passed to async.forEachOf is an array to iterate over it (obj).
  2. The 2nd parameter is a callback function that apply over each item in obj.
  3. The 3rd or the last parameter that is passed to async.forEachOf function, is another callback function too. It is called when iteration process over every item in obj has finished.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM