ionic custom form builder

Ionic Custom Form Builder

January 6, 2020
easily view your laravel logs using laravel log viewer

Easily View Your Laravel Logs Using Laravel Log Viewer

January 31, 2020

How I Like To Use Async Await In JS

January 27, 2020 / Tielman Janse van Vuuren

Using async and await is generally considered to be a replacement for handling promises with then() and catch() methods:

methodThatReturnsAPromise().then(result => {
  handleResult(result)
}).catch(err => {
  handleAnyExceptions(err)
})

The promise handler shown above can be replaced with the following in an async function:

methodThatReturnsAPromise().then(result => {
  handleResult(result)
}).catch(err => {
  handleAnyExceptions(err)
})

But this method doesn’t handle errors that can come through in the then() function. Also in my opinion try ... catch leans towards arrow code. Luckily await expects a promise so we can combine promise handling with async await:

var err, result
[err, result] = await methodThatReturnsAPromise().then(res => [null, res], error => [error]).catch(error => {err = error})

if(err != null) {
  handleAnyExceptions(err)
} else if(result != null) {
  handleResult(result)
}

Any errors will end up in the err variable and the result will be in the result variable. This allows you to harness the power of async await to avoid callback hell, while being able to handle errors cleanly.

Share

Tielman Janse van Vuuren

Tielman is an experienced mobile and backend developer. Quality is his motto, no matter what programming language or platform.

How I Like To Use Async Await In JS
This website uses cookies to improve your experience. By using this website you agree to our Data Protection Policy.
Read more