javascript中的承诺链需要中断或完成吗
我正在寻找一种技术,可以在承诺链(或finish()或类似的东西,某种终端方法)上切换到最后一个catch(),而不必维护“completed”状态变量和我现在使用的伪finished()承诺,它要求在每次捕获和finished()之后检查状态变量被(再次)抛出。使用某种“下降到最后一次捕获”的方法,在一个链中读取和维护该过程会容易得多。目前,我使用的是纯ES6,但其他LIB将得到充分考虑 简言之,我该怎么做javascript中的承诺链需要中断或完成吗,javascript,promise,es6-promise,Javascript,Promise,Es6 Promise,我正在寻找一种技术,可以在承诺链(或finish()或类似的东西,某种终端方法)上切换到最后一个catch(),而不必维护“completed”状态变量和我现在使用的伪finished()承诺,它要求在每次捕获和finished()之后检查状态变量被(再次)抛出。使用某种“下降到最后一次捕获”的方法,在一个链中读取和维护该过程会容易得多。目前,我使用的是纯ES6,但其他LIB将得到充分考虑 简言之,我该怎么做 begin() // some promise method .then() .the
begin() // some promise method
.then()
.then(/* found out I'm done here - break out or drop to last then() */)
.then()
.then()
.catch()
你不应该仅仅通过返回一个被拒绝的承诺来打破承诺链吗
begin()
.then(() => {
if (/*we're done*/) {
return Promise.reject('some reason');
}
})
.then() // won't be called
.catch() // Catch 'some reason'
你不应该仅仅通过返回一个被拒绝的承诺来打破承诺链吗
begin()
.then(() => {
if (/*we're done*/) {
return Promise.reject('some reason');
}
})
.then() // won't be called
.catch() // Catch 'some reason'
您可以从函数中抛出异常
var p=Promise.resolve();
p、 然后(()=>console.log(1))
.then(()=>{console.log(2);抛出'Oh no!';})
.然后(()=>console.log(3))
.catch(错误=>console.log(错误))代码>您可以从函数中引发异常
var p=Promise.resolve();
p、 然后(()=>console.log(1))
.then(()=>{console.log(2);抛出'Oh no!';})
.然后(()=>console.log(3))
.catch(错误=>console.log(错误))代码>我们可以通过抛出错误来打破承诺链
function myFunction() {
// our custom promise or some function return promise object
return new Promise(function(resolve,reject){
setTimeout(function(){
resolve('dai')
}, 2000)
})
}
myFunction().then(data=>{
console.log('main')
}).then(data =>{
console.log('one')
}).then(data =>{
console.log('two')
throw new Error('custom breaked')
}).then(data =>{
console.log('three')
}).catch(err=>{
console.log('---------error---------')
console.log(err.message) // custom breaked
res.status(500).send(err.message);
})
我们可以通过抛出错误来打破承诺链
function myFunction() {
// our custom promise or some function return promise object
return new Promise(function(resolve,reject){
setTimeout(function(){
resolve('dai')
}, 2000)
})
}
myFunction().then(data=>{
console.log('main')
}).then(data =>{
console.log('one')
}).then(data =>{
console.log('two')
throw new Error('custom breaked')
}).then(data =>{
console.log('three')
}).catch(err=>{
console.log('---------error---------')
console.log(err.message) // custom breaked
res.status(500).send(err.message);
})
如果你的第二个,那么
在你发现你没有完成时返回一个承诺?不。不是一个有用的承诺。如果你的第二个那么
在你发现你没有完成时返回一个承诺?不。不是一个有用的承诺。是的。考虑了一个“完成”异常,但我想确保在将异常用作正常的控制流机制之前没有遗漏一些基本内容。如果在未完成时提供承诺对象,则可以在第二个中继续此流(…)
。是的,这意味着嵌套其余的then()
调用,在我的书中,这是完全正确的。考虑了一个“完成”异常,但我想确保在将异常用作正常的控制流机制之前没有遗漏一些基本内容。如果在未完成时提供承诺对象,则可以在第二个中继续此流(…)
。是的,这意味着嵌套其余的then()
调用,在我的书中,这是完全正确的