使用try和catch在异步函数中设置超时不会捕获错误

时间:2018-09-11 23:38:03

标签: javascript asynchronous ionic-framework ionic3 es6-promise

我有一个 Ionic 3 App ,在其中我将async and await的ES6功能用于promises的语法糖。我知道这只是一些基本问题,或者因为我刚使用 async and await 功能。

现在的问题是,我的setTimeout n方法的异步函数中有一个signI,用于验证用户。

这是我的下面的代码:

async signIn() {
    try {
      this.loader = true // Present a loader
      this.backgroundLoader = this.loadingCtrl.create({ content: 'Signing you in...' });
      this.backgroundLoader.present();
      // Response from server
      const response: any = await this.authService.loginDriver(this.loginForm.value)
      console.log(response)
      if (response.status == 200) { // If success response
        const token = await this.storage.set('token', response.data.token)
        console.log('token:', token)
        this.events.publish('driver:authenticated') // Broadcast an event that the driver has authenticated
        setTimeout(async () => {  // Dismiss the loader after successfull authentication
          try {
            const meDetails = await this.driverMe.getDriverMeInfo() // Get the profile information of the driver if
            console.log(meDetails)
          } catch (err) { console.log(err) } 
          this.backgroundLoader.dismiss();
          this.loader = false 
          this.navCtrl.setRoot("HomePage")
          this.menu.swipeEnable(true);
        }, 1500);
      }
    } catch(err) { // If something goes wrong or an error occured
      console.log(err)
      this.backgroundLoader.dismiss();
      this.loader = false 
      err.status == 401 || 422 // Something wrong in your authentication credentials
        ? this.alertMessage.alertMessage('Incorrect email or password', null) 
        : this.alertMessage.alertMessage('Something went wrong.', 'Please try again.') // Other errors not related to the data entry to be authenticated
    }
  }

该功能执行基本的身份验证,以将发布请求发送到 API服务器,并获取响应令牌并将其放在< strong>存储,并在后端中将令牌用于需要身份验证中间件的每个请求。

实际上,在我的代码中没有错误,效果很好。但是,如果您查看try and catch方法内部的setTimeout。看起来很丑。 try and catch的目的是为每个 promise (错误)捕获一个错误,但是我将在setTimeout函数中再次声明它。

我不确定,但是我认为这是由于setTimeout上的回调函数是新的async and await而引起的,这就是为什么它不会捕获错误的原因。

所以我的问题确实有办法解决吗?为了避免在 setTimeout 方法中重新声明try and catch

感谢有人可以帮助您。 预先感谢。

反正有一个try and catch

0 个答案:

没有答案
相关问题