This is a small utility to make handling promises a little more readable. Avoiding Towers of Terror and Pyramids of Doom.
resolve()
takes the promise
to resolve as its first argument, optionally takes a boolean for the second parameter; convertToError
, finally it optionally takes the parameters of JSON.stringify
(save for the first) as the remaining parameters, to be used when stringifying errors.
If convertToError
is
-
true
, and an error is given that's not an instance ofError
,resolve()
will return an instance ofError
with the given error stringified on themessage
property. - given a falsy value, instances of
Object
andError
will be returned as-is, while primitives will be treated as iftrue
was provided. This is the default behavior. - explicitly
false
, the error will always be returned as-is. If you wish for this to be the default behavior, import the named exportresolve
rather than using the default export.
resolve()
returns a tuple; [res, err]
. Where res
is the result of the promise, and err
is an error, if one was encountered. The values are mutually exclusive, so if one is defined, the other will be undefined
.
import resolve from "resolvjs"
import anAsyncFunction from "some-api-client"
const [res, err] = await resolve(anAsyncFunction())
if (err) throw err // or handle it in some other way
console.log(res)
resolve()
is a generic function, enabling you to specify the type of the result in such cases where it cannot be or is incorrectly inferred. However, the returned type for res
will always be R | undefined
, this allows you to use a guard pattern, as shown below, to ensure that errors are always handled. After which, res
will be of type R
.
import resolve from "resolvjs"
import anAsyncFunction from "some-api-client"
import type { SuccessResponse } from "some-api-client/types"
const [res, err] = await resolve<SuccessResponse>(anAsyncFunction())
if (err) throw err // or handle it in some other way
console.log(res)
resolve()
can also take a type parameter for err
. When using the default export, this results in err
being of type E | Error | undefined
, the example below shows how err
can be inferred as E
. When using the named export and no type parameter is provided, err
will be of type unknown
. However if a type parameter is provided, it will be of type E | undefined
.
import resolve from "resolvjs"
import anAsyncFunction from "some-api-client"
import type { SuccessResponse, ErrorResponse } from "some-api-client/types"
const [res, err] = await resolve<SuccessResponse, ErrorResponse>(anAsyncFunction(), false)
if (err) {
if ("errorProp" in err) {
throw err.errorProp
}
throw err
}
console.log(res)
Inspiration for this project came from the Fireship short Async Await try-catch hell and uses the solution presented nearly verbatim.