Javascript 如何使用node.js中的q.defer链接承诺?

Javascript 如何使用node.js中的q.defer链接承诺?,javascript,node.js,promise,q,Javascript,Node.js,Promise,Q,这是我的密码。如果有一个位置\父\ id,那么我也想返回该位置。我认为承诺是执行我想要的东西的好方法,而不是陷入异步和回调的地狱。只是不确定具体如何使用。您根本不需要使用q.defer。您可以使用该选项立即获得承诺。要链接这些方法,请使用。然后 您根本不需要使用q.defer。您可以使用该选项立即获得承诺。要链接这些方法,请使用。然后 你用它来连锁承诺。使用q.defer只创建它们(如果有的话)。您使用then来链接承诺。使用q.defer只能创建它们(如果有的话)。有一个奇怪的`}.catch

这是我的密码。如果有一个位置\父\ id,那么我也想返回该位置。我认为承诺是执行我想要的东西的好方法,而不是陷入异步和回调的地狱。只是不确定具体如何使用。

您根本不需要使用q.defer。您可以使用该选项立即获得承诺。要链接这些方法,请使用。然后

您根本不需要使用q.defer。您可以使用该选项立即获得承诺。要链接这些方法,请使用。然后


你用它来连锁承诺。使用q.defer只创建它们(如果有的话)。您使用then来链接承诺。使用q.defer只能创建它们(如果有的话)。有一个奇怪的`}.catch`请不要抛出字符串,而有些承诺会四处传播,以便为它们提供堆栈跟踪——这是一种不好的做法。此外,Q不是这些库中的一个,当抛出string@BenjaminGruenbaum:谢谢你提醒我!现在好多了?是的,顺便说一句,聪明的解决办法。唯一让我困扰的是现在的性能,但这是一个Q问题,而不是承诺或解决方案问题:哦,还有一件事,if中使用了location\u parent\u id,但您没有定义它,因为您将它移动到了。ninvokethen没有定义在:}.donethenfunctionresponse{有一个奇怪的`}.catch`请不要抛出字符串,而有些承诺会四处传播,以便为它们提供堆栈跟踪——这是一种不好的做法。此外,Q不是这些库中的一个,当抛出string@BenjaminGruenbaum:谢谢你提醒我!现在好多了?是的,顺便说一句,聪明的解决办法。唯一困扰我的是现在的性能,但这是一个Q问题,而不是承诺或解决方案问题:哦,还有一件事,if中使用了location\u parent\u id,但您没有定义它,因为您将它移动到了。ninvokethen未在:}.donethenfunctionresponse上定义{
exports.list = function(req, res) {
  var location_parent_id = req.params.location_parent_id;

  var query = {
    company_id: req.company_id
  };

  if(location_parent_id) {
    query.location_parent_id = location_parent_id;
    Location.findOne({someQuery}, function(err, location) {
      response.location = location;
    });
  } else {
    query.location_parent_id = {
      '$exists': false
    }
  }

  Location.find(query, function(err, locations) {
    if(err) {
      response = {
        status: 'error',
        error: err
      }
    } else if(!locations) {
      response = {
        status: 'error',
        error: 'Location not found'
      }
    } else {
      response = {
        status: 'ok',
        locations: locations
      }
      return res.json(response);
    }
  });
}
exports.list = function(req, res) {
  var result = Q.ninvoke(Location, "find", {
    company_id: req.company_id,
    location_parent_id: req.params.location_parent_id || {'$exists': false}
  }).then(function(locations) {
    if (!locations)
      throw new Error('Location not found');
    return {
      status: 'ok',
      locations: locations
    };
  });
  if (req.params.location_parent_id) {
    // insert the step to wait for the findOne (in parallel), and merge into res
    result = Q.all([result, Q.ninvoke(Location, "findOne", {someQuery})])
    .spread(function(res, location) {
      res.location = location;
      return res;
    });
  }
  result.catch(function(err) {
    return {
      status: 'error',
      error: err.message
    };
  }).done(function(response) {
    res.json(response);
  });
}