打破当时的承诺链

时间:2018-03-27 15:42:12

标签: angular typescript

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

我的代码:

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 }) }
    )
}

1 个答案:

答案 0 :(得分:3)

您可以使用catch()方法:通过执行此操作,您将处理来自您的承诺链的任何错误。当你的链条中的任何地方发生错误时,它会"中断"来自promise链,最后是catch方法。 MDN: .catch() method

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*/})
}