如何在下一个.then()中访问包含错误的被拒绝对象?

时间:2017-10-19 04:43:55

标签: javascript node.js promise

我有一系列承诺,我希望在某个承诺中记录错误,但将其余数据传递给下一个.then()

    const parseQuery = (movies) => {
    return new Promise((resolve, reject) => {
      const queries = Object.keys(req.query).length;
      if(debug) console.log('Parsing ', queries ,'queries');
      if(queries > 0) { //If there's any query run this
        //When calling two parameters
        if(req.query.index && req.query.trailer) reject(errorify('You can\'t call two parameters at once.'));
        //When calling index
        else if(req.query.index){
          var index = Number(req.query.index);
          if(debug) console.log('Calling index ',index);
          if(index<movies.length && index>=0){ //Index is a number and in range
            movie = movies[index];
            movie.index = index;
          }
          else if(isNaN(index) || index <= 0 || index>movies.length) {
            let index = random.exclude(0,movies.length-1);
            movie = movies[index];
            reject({
              msg: errorify('Index is not a number or it\'s out of range.'),
              movie //Add the var as a property
             });
          }
          if(debug) console.log('Requested: ', movie.title);
          }
        //When calling trailer
        else if(req.query.trailer){
          movie = {title: req.query.trailer};
        }
        resolve([movie]); //Pass the result as a one item array
      }
      else {
        resolve(movies); //If no query is called just pass the movies through
      }
     });
  };

  readDB(file)
    .then(parseQuery)
      .then(
        result => { selectMovie(result); },
        reason => { console.log(reason.err); selectMovie(reason.movie); 
});

由于某种原因,result工作正常,但当我尝试访问对象属性(reason.errreason.movie)时,原因给我未定义但是当我调用对象时它给了我这个原因是:

    Error:  { msg: 
   Error: Index is not a number or it's out of range. Selecting a random movie.
       at errorify (/Users/gonzo/Projects/JS/random-movie-trailer/src/controllers/routes.js:16:10)
       at Promise (/Users/gonzo/Projects/JS/random-movie-trailer/src/controllers/routes.js:61:20)
       at Promise (<anonymous>)
       at parseQuery (/Users/gonzo/Projects/JS/random-movie-trailer/src/controllers/routes.js:43:12)
       at <anonymous>
       at process._tickCallback (internal/process/next_tick.js:169:7),
  movie: { title: 'The Hero', usersScore: '77%', criticsScore: '64%' } }

所以我可以看到reason是一个带有msg属性的Error对象,也是一个错误。

然后我的问题。如果拒绝obj同时传递错误和电影是没有解决方案我怎么能将两个值传递给下一个Promise?这样我就可以使用reason.errreason.movie

1 个答案:

答案 0 :(得分:0)

最后,我选择避免抛出错误并使用@jfriend00告诉我的内容:我现在发送的对象仅附加msg如果有“错误”并且在处理输出的函数中我放了一个if语句来检查对象是否有msg属性。像这样:

if(movies.msg) {
   console.log('Index :',movies.index);
   console.error(movies.msg);
   movies = [movies.movie];
}

selectRandom(movies)
  .then(requestTrailer)