Javascript 从特定承诺有条件地启动承诺链
我有一个简化的承诺链,如下所示:Javascript 从特定承诺有条件地启动承诺链,javascript,node.js,promise,Javascript,Node.js,Promise,我有一个简化的承诺链,如下所示: readDB(file) .then(parseQuery) .catch((err) => console.error(err)) .then(selectRandom) .catch((err) => console.error(err)) .then(requestTrailer) .catch((err) => { if(err == 'Got error: No results found') { th
readDB(file)
.then(parseQuery)
.catch((err) => console.error(err))
.then(selectRandom)
.catch((err) => console.error(err))
.then(requestTrailer)
.catch((err) => {
if(err == 'Got error: No results found') {
throw new Error(err);
}
})
.then(renderMovie)
.catch((err) => console.error(err));
基本上,我是从一个文件中读取电影列表,并将其传递给大家,以便找到电影的预告片。我不想做的是在出现错误的情况下,从selectRandom on开始重复承诺链,而不必读取DB和parseQuery
现在我有一个工作代码,但它定义了两次链:
//I wrap the second round of promises in a function
selectMovie(){
selectRandom(movies)
.then(requestTrailer)
.catch((err) => {
if(err == 'Got error: No results found') {
selectMovie(); //Start the function again
throw new Error(err);
}
})
.then(renderMovie)
.catch((err) => console.error(err));
}
//Now start the promise chain
readDB(file)
.then(parseQuery)
.catch((err) => console.error(err))
.then(selectRandom)
.catch((err) => console.error(err))
.then(requestTrailer)
.catch((err) => {
if(err == 'Got error: No results found') {
selectMovie(); //Start second round
throw new Error(err);
}
})
.then(renderMovie)
.catch((err) => console.error(err));
有更简单的方法吗?替换。然后通过调用selectMovie函数选择Random及其后的所有内容 听起来你只是想擦干你的代码,但你部分地这么做了,所以要么我误解了,要么你错过了显而易见的东西。你不能用selectMovie替换底部的部分代码吗?比如readDB然后parseQuery然后selectMovie?选择电影是否应该有return关键字?或者就这样?我认为selectMovie不需要返回语句,除非您想在之后添加更多承诺链,但通常最好返回一些东西。但是,是的,移动它,尝试一下,看看会发生什么。我错过了显而易见的。它工作得很好哈哈,每个人都有。你介意接受我刚才补充的答案吗?