Skip to content

How async await works

Devrath edited this page Oct 11, 2021 · 6 revisions

Challenge in asynchronous code

  • One of the biggest challenges in asynchronous programming is returning values from it.
  • This is a challenge because once you call the function, you don't know when to return.
  • This is hard to achieve on communicating between the threads.

Leveraging async/await pattern

  • Using the async/await pattern we can perform tasks in parallel.
  • Tasks that are not blocking.
  • Best part is they can return the values.

Inspiration to async/await pattern

  • Using the promise pattern
    • There the flow is like then(do something) --> then(do something) --> then(do something) --> . --> catch(if errors)
    • As simply explained in the above flow, we perform action after action, and during this time if there is an error, we catch the error down the stream in the catch block
    • Disadvantages associated with promise for android include, Since the promise doesn't return a value and returns a promise, This is not suitable for the android type of programming.
  • Using the future pattern
    • Future is much similar to promise and they behave similarly.
    • When you create a future, you are not promising, some value will be there down the line. Remember promises are easy to break.
    • In promise it's just a possibility that something will exist, a promise can be broken.
    • In promise you miss a return call and everything can be broken, In turn freezing the entire call.
    • In future, you need to mention the return type otherwise there will be a compile-time error.
Clone this wiki locally