【发布时间】:2018-04-10 05:04:17
【问题描述】:
我有一个承诺链,在某个承诺中,我希望它记录错误,但将其余数据传递给下一个 .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.err、reason.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 属性的错误对象,它也是一个错误。
然后我的问题。如果拒绝一个 obj 来传递错误和电影都不是解决方案,我怎么能将这两个值传递给下一个 Promise?这样我就可以使用reason.err 和reason.movie
【问题讨论】:
-
请向我们展示创建原因对象的整个代码。
console.log(reason)的假定结果与reject({err: new Error('Error'), movie})行完全不匹配。 -
resolve()和reject()如何与.then()关联到readDB(file)? “//Previous reject and result”是什么意思? -
假设是
parseQuery()创建了这个被拒绝的promise,那就是可以将任何它想要的东西放入rejectreason的代码。我还建议,如果这不是真正的“失败”,而只是不同的返回条件,您可能想要更改已解决的值,以便您可以在那里处理两种类型的返回并保存拒绝状态实际失败。 -
我写得不好。对不起://以前的拒绝和结果是原因和结果的创建者。我会更新我的代码
标签: javascript node.js promise