表达错误处理承诺

时间:2018-04-09 14:07:31

标签: node.js express mongoose promise

当jobs为null时,错误会被处理,但是在它继续到promises链之后。如果出现错误,我如何打破promise链?我使用默认的快速错误处理程序。

search.route('/:job/:lng/:lat')
.get((req, res, next) => { 
   Jobs.findOne({"names":req.params.job})
  .then((job) => {
    if(!job){
      err = new Error("Job "+req.params.job+" doesnt exist...Will look on it");
      err.status = 404;
      return next(err);
    }
    else{
    return(job.id);
    }

    }, (err) => next(err))
  .then((jobId) => {
   return( 
      Professionals.aggregate([

      { "$geoNear": {
          "near": {
              "type": "Point",
              "coordinates": [Number(req.params.lng),Number(req.params.lat)]
          },
          "distanceField": "distance",
          "spherical": true,
          "maxDistance": maxDistance

      }}]

    ) 
  );

  }, (err) => next(err))
  .then((pros) => {
      for(i=0;i <= pros.length -1;i++){
        if(pros[i].distance > pros[i].location.radius ){
          pros.splice(i,1); 

        }

      }

      res.statusCode = 200;
      res.setHeader('Content-Type', 'application/json');
      res.json(pros);
  }, (err) => next(err))
  .catch((err) => next(err));

});

提前致谢!!

1 个答案:

答案 0 :(得分:0)

使用throw,它完全适合这种情况。当你创建一个新的Promise时,你应该使用reject:

new Promise((resolve, reject) => reject());