Gracefully handle a Promise using async/await.
With the addition of async/await keywords in ECMAScript 2017 the handling of Promises became much easier. However, one must keep in mind that the await keyword provides no standard error handling API. Consider this usage:
asyncfunctiongetUser(id){constdata=awaitfetchUser(id)// Work with "data"...}In case fetchUser() throws an error, the entire getUser() function's scope will terminate. Because of this, it's recommended to implement error handling using try/catch block wrapping await expressions:
asyncfunctiongetUser(id){letdata=nulltry{data=awaitasyncAction()}catch(error){console.error(error)}// Work with "data"...}While this is a semantically valid approach, constructing try/catch around each awaited operation may be tedious and get overlooked at times. Such error handling also introduces separate closures for execution and error scenarios of an asynchronous operation.
This library encapsulates the try/catch error handling in a utility function that does not create a separate closure and exposes a NodeJS-friendly API to work with errors and resolved data.
npm install until-asyncimport{until}from'until-async'asyncfunctiongetUserById(id){const[error,data]=awaituntil(()=>fetchUser(id))if(error){returnhandleError(error)}returndata}import{until}from'until-async'interfaceUser{firstName: stringage: number}interfaceUserFetchError{type: 'FORBIDDEN'|'NOT_FOUND'message?: string}asyncfunctiongetUserById(id: string){const[error,data]=awaituntil<UserFetchError,User>(()=>fetchUser(id))if(error){returnhandleError(error.type,error.message)}returndata.firstName}This has been intentionally introduced to await a single logical unit as opposed to a single Promise.
// Notice how a single "until" invocation can handle// a rather complex piece of logic. This way any rejections// or exceptions happening within the given function// can be handled via the same "error".const[error,data]=awaituntil(async()=>{constuser=awaitfetchUser()constnextUser=normalizeUser(user)consttransaction=awaitsaveModel('user',user)invariant(transaction.status==='OK','Saving user failed')returntransaction.result})if(error){// Handle any exceptions happened within the function.}- giuseppegurgone for the discussion about the original
untilAPI.