繁体   English   中英

突破承诺链

[英]Breaking out of then promise chain

如何突破Promise链(处理错误并停止运行其他.then)?

我的代码:

onSubmit(f: any) {
    let loading = this.loadingCtrl.create({
        content: 'Sending a form...'
    });
    loading.present();
    this.submitProvider.sendByPost(f)
    .then(
        (res) => { this.formSent = true, console.log('Form is sent') },
        (err) => { console.log('Encountered an error...') 
            //error here, break out and deal with error            
        } 
    )
    .then( (res) => {
        loading.dismiss();
        this.pushPage(); 
        this.removeChosenPicture();
        this.removeTakenPicture();
        this.myForm.reset({ selectedDate: this.selectedDate }) }
    )
}

您可以使用catch()方法:通过这样做,您将处理promise链中的所有错误。 当错误在链中的任何地方抛出时,它将“脱离” promise链并最终以catch方法结束。 MDN:.catch()方法

onSubmit(f: any) {
    let loading = this.loadingCtrl.create({
        content: 'Sending a form...'
    });
    loading.present();
    this.submitProvider.sendByPost(f)
    .then(
        (res) => { this.formSent = true, console.log('Form is sent') }
    )
    .then( (res) => {
        loading.dismiss();
        this.pushPage(); 
        this.removeChosenPicture();
        this.removeTakenPicture();
        this.myForm.reset({ selectedDate: this.selectedDate }) }
    ).catch((err) =>{ /*Handle your errors*/})
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM