DennisTurn DennisTurn - 5 months ago 9
Node.js Question

Express router callbacks

I'm a little new to Express/Node.js/Mongoose and I've ran into callback hell. What I'm trying to do is get a request in to this API URL

/page/module/add/:id
, if successful call
buildMod(data)
, then that function calls
getMod(data)
, and then that function calls
writeMod(data)
and eventually I want to pass the
true
value right back up to my
router
.

Once I have the response, I want to return it. I've searched online and there's not many similar situations--I personally think I've got myself in too deep...

router.get('/page/module/add/:id', function(req, res) {
Client.find({"emailAddress": emailAddress, "sequence.slug": pageSlug},
{"emailAddress": 1, "sequence.$": 1}, function (err, data) {
if (!err) {
res.statusCode = 200;

buildMod(data);

return res.json(data);
} else {
res.statusCode = 500;

log.error('Internal error(%d): %s', res.statusCode, err.message);

return res.json({
error: 'Server error'
});
}
}).select('sequence emailAddress domain');
});


function buildMod(data) {
getMod(data);
}

function getMod(data) {
Module.find({ 'module_id': moduleNumID }, function (err, module) {
if(!module) {
return false;
}

if (!err) {
writeMod(data);
} else {
return false;
}
});

}

function writeMod(data) {
fs.appendFile(location, content, function(err) {
if (err) throw err;
return true;
});
}


I know the declarations are wrong for the functions for callbacks but I've been trying and I just can't seem to get past this stage. I'm sure this is definitely possible, any help is really appreciated!

Answer

fs.appendFile is asynchronous and you can not return from asynchronous calls.

Make use of callback

router.get('/page/module/add/:id', function(req, res) {
  Client.find({
    "emailAddress": emailAddress,
    "sequence.slug": pageSlug
  }, {
    "emailAddress": 1,
    "sequence.$": 1
  }, function(err, data) {
    if (!err) {
      res.statusCode = 200;
      buildMod(data, function(data) {
        res.json(data);
      });
    } else {
      res.statusCode = 500;
      log.error('Internal error(%d): %s', res.statusCode, err.message);
      return res.json({
        error: 'Server error'
      });
    }
  }).select('sequence emailAddress domain');
});


function buildMod(data, cb) {
  getMod(data, cb);
}

function getMod(data, cb) {
  writeMod(data, cb);
}

function writeMod(data, cb) {
  fs.appendFile(location, content, function(err) {
    if (err) throw err;
    cb(true);
  });
}