Question

I'm attempting to write a simple validation script in Node where error codes are added to an error array when certain validation checks fail. To complicate things, I also have a function called translate which makes a database call and returns the full text associated with an error code (translated into the specified language). In order to achieve this, I'm using the async library.

Unfortunately, the following code always results in an empty array, even when validation should fail. I've confirmed independently that my translate function works. Any ideas why this isn't working?

app.post("/user", function(req, res) {

  var error = [];

  if (req.body.username == "") {
    error.push("username_required");
  }

  if (req.body.password == "") {
    error.push("password_required");
  }

  for (var i = 0; i < error.length; i++) {
    error[i] = function(callback) {
      translate(error[i], req.language, function(text) {
        callback(null, text);
      });
    };
  }

  async.parallel(error, function(error, results) {
    res.send(results);
  });

});

translate = function(code, language, callback) {
  var code = database.escape(code);
  var language = database.escape(language);
  database.query("SELECT content FROM text WHERE language = 'en' AND code = " + code, function(error, row) {
    callback(row[0].content);
  });
}
Was it helpful?

Solution

As suggested in the comments, async.map did the trick. Here's my final solution:

app.post("/user", function(req, res) {

  var error = [];

  if (!req.body.username) {
    error.push("username_required");
  }

  if (!req.body.password) {
    error.push("password_required");
  }

  async.map(error, function(error, callback) {
    translate(error, req.language, function(text) {
      callback(null, text);
    });
  }, function(error, results) {
    res.send(results);
  });

});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top