AJS AJS - 3 days ago 4
Javascript Question

Transform code in promises

This my code where I have dependent callbacks:

db.collection(config.user).find({
"_id": id,
}, function(err, result) {
if (!err) {
db.collection(config.user).update({
'_id': uname,
"pass": pwd
}, {
$set: {
'pass': pwd
}
}, function(err1, result1) {
db.close();
if (!err1) {
res.json({
"success": 1)
} else {
logger.error(err);
}
});
} else {
logger.error(err);
}
});


How could this code be written using promises?

Answer

You can do this in this way:

function findUser(user, id) {
  db
    .collection(user)
    .find({ "_id": id }, function (err, result) {
      if (err) {
        return Promise.reject(err);
      }

      return Promise.resolve(result);
    });
}

function updateUser(user, uname, pwd) {
  db
    .collection(user)
    .update({
      '_id': uname,
      "pass": pwd
    }, {
      $set: {
        'pass': pwd
      }
    }, function (err, result) {
      db.close();

      if (err) {
        return Promise.reject(err);
      }

      return Promise.resolve(result);
    });
}

Promise
  .all([findUser(config.user, id), updateUser(config.user, uname, pwd)])
  .then(function (results) {
    res.json({ "success": 1 });
  })
  .catch(function (errors) {
    logger.error(errors);
  });
Comments