1

I have an Ionic 3 App where I use async and await of ES6 features for syntactic sugar of promises. I know this is just a little bit basic question or because I am just new in using async and await feature.

Now the problem is I had a setTimeout inside my async function of signIn method to authenticate the user.

This is my code below:

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

The function does a basic authentication to send a post request to an API server and get the response token and put it on a Storage and use that token for every request that needs authentication middleware in the backend.

Actually there is no error in my code it works great. But if you look at the try and catch inside the setTimeout method. It looks uglier. The purpose of the try and catch is to catch an error for every promises but I am redeclaring it again inside the setTimeout function.

I'm not sure but I think this is happening because of the callback function on the setTimeout is a new async and await that's why it wont catch the error outside.

So my question really is there a way to handle this? To avoid redeclarations of try and catch inside a setTimeout method.

Appreciate if someone could help. Thanks in advance.

Is there anyway to handle this using one try and catch

KnowledgeSeeker
  • 1,058
  • 2
  • 19
  • 44
  • You have to get rid of the raw `setTimeout` and wrap it with a promise, so that it integrates with `async`/`await`. See this thread: https://stackoverflow.com/a/33292942/14955 – Thilo Sep 11 '18 at 23:50
  • @Thilo so I would make a setTimeout function in a generic way and wrap it into a promises then pass the milliseconds as a argument right? and execute the next line of function after that. – KnowledgeSeeker Sep 11 '18 at 23:53
  • You'd want to `await` the promise returned from your timeout. If you don't, it will not catch any exceptions. – Thilo Sep 11 '18 at 23:56

0 Answers0