Riza Masta Riza Masta - 3 months ago 10
Node.js Question

the variable i is not filled

I have declare the variable first. but if I do

console.log(userinsertData)
outside looping variable still not fill.
what i should do for solving this problem?
here my code:

var User = require('../models/user');

module.exports = {
myaction: function(req, res, next) {
var data = req.body,
userinsertData = [];
try {
data.forEach(function(item, index) {
var userdata = new User();
userdata.name = item.name;
userdata.age = item.age;
userdata.sex = item.sex;
userdata.save(function(err, data) {
if (err) {
res.send(err)
} else {
userinsertData.push(data);
}
});
})
} catch (e) {
res.json({
message: 'data not valid'
})
}
console.log(userinsertData);
res.json({
message: 'musician created!',
data: userinsertData
});
}
};

Answer

Use promise

var User = require('../models/user');

module.exports = {
  myaction: function(req, res, next) {
    var data = req.body,
      userinsertData = [];

    new Promise(function(resolve, reject) {
      data.forEach(function(item, index) {
        var userData = new User(item);
        userData.save(function(err, data) {
          // if error, reject
          if(err) return reject(err);
          // we have proceed all items in data, resolve it
          else if(data.length - 1 === index) return resolve(userinsertData);
          // not finished yet, keep proceeding
          else userinsertData.push(data);
       });
    }).then(function(successResult) {
      res.json({
        message: 'musician created!',
        data: successResult
      });
    }, function(errorResult) {
      res.json({
        message: 'data not valid'
      });
    });
  }
};

Use callbacks

var User = require('../models/user');

module.exports = {
  myaction: function(req, res, next) {
    var data = req.body,
      userinsertData = [];

    function saveUser(callback) {
      data.forEach(function(item, index) {
        var userData = new User(item);
        userData.save(function(err, data) {
          // if error, return callback with error
          if(err) return callback(err);
          // we have proceed all items in data, return data
          else if(data.length - 1 === index) callback(null, userinsertData);
          // not finished yet, keep proceeding
          else userinsertData.push(data);
       });
    }

    saveUser(function(err, users) {
      if(err) return res.json({message: 'data not valid'});
      res.json({
        message: 'musician created!',
        data: users
      });
    });
  }
};

This is what async package does internally