Ionic Custom Form Builder
January 6, 2020Easily View Your Laravel Logs Using Laravel Log Viewer
January 31, 2020Using 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.