How do I rewrite a series of conditional statements with Q promises in node.js?

前端 未结 2 1894
后悔当初
后悔当初 2021-01-20 12:30
exports.create = function(req, res) {
  var company_id = req.company_id;
  var client = new Client(req.body);

  Company.findOne({_id: company_id}, function(err, com         


        
2条回答
  •  野的像风
    2021-01-20 13:05

    This is not really the use case for Promises. Promises are a method for eliminating deeply nested callbacks in node.js, not complex logic dealing with a result, like you have in your code. Think of the case where the outcome of your .findOne query would determine the next query you need to make - this quickly leads to a nested callback situation, which can be made less nested and more natural to read, evaluate, re-factor, and build upon if you use Promises.

    You do have one nested callback for the outcome of your .save call. So, you might successfully re-factor this using Promises, like so

    new Promise(function() {
        Company.findOne()
        ...
    .then(function(company) {
        company.update()
        ...
    }, function(err) {
        ...
    })
    

    The starting point is to wrap your first query so that it returns a promise instead of dealing with callbacks within callbacks.

提交回复
热议问题