Alternative to promises of asynchronous callouts?

10,426

You can use async/await. It's the only alternative to classical .then() promise handling.

So, instead of doing this:

someServiceMethod() {
  repository.makeTheGetCall().then(function (response) {
    // process response
  }); 
}

You can do this:

async someServiceMethod() {
  const response = await repository.makeTheGetCall()
  // process response
}

The coolest thing is that we don't have any starting point for "callback hell", code is now flat (#1 in your list)

Also, if one of the Promises was rejected, we can handle the error in try/catch block. The good thing about it that we can have one place to catch all errors. (#2 in your list):

async someServiceMethod() {
  try {  
    const response = await repository.makeTheGetCall()
    const data = await repository.getDataForResponse(response)
    // process data or make another async call
  } catch (err) {
    // process error
  }
}

Good explanation of how to use it

Share:
10,426
junvar
Author by

junvar

I'm a dev!

Updated on June 04, 2022

Comments

  • junvar
    junvar almost 2 years

    Assume we have a simple front end and (let's assume Angular if it matters) and a back end app. Say the front end app does a get request. Usually the angular repository makes an $http.get request which returns a promise (angular 1) or an observable that can be converted to a promise (angular 2 or 4), and then the repository returns that promise. Then the angular service will look something like

    repository.makeTheGetCall().then(function (response) {
      // process response
    }); 
    

    This is fine usually.

    1) But what if all the logic on the service is dependent on this 1 call? Then we've essentially nested the entirety of the service within a .then clause.

    2) Or what if based on the response of the first Get request, we make another request. And based on that response, we make another request, and so on. Then we will have a bunch of then clauses chained.

    Neither situations seems that rare, and both result in what appears to be 'ugly' code. Is there any other practice that can be used so to allow asynchronous calls but without having to return promises from the repository layer to the service layer?

    Thank you :)