Skip to content

Instantly share code, notes, and snippets.

@justforuse
Last active November 27, 2023 05:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justforuse/d2a0e9ed917a76244ee73e0cd883fbea to your computer and use it in GitHub Desktop.
Save justforuse/d2a0e9ed917a76244ee73e0cd883fbea to your computer and use it in GitHub Desktop.
safe await
export function safeAwait(promise, finallyFunc) {
return promise.then(data => {
return [ undefined, data ]
}).catch(error => {
return [ error, undefined ]
})
}
@justforuse
Copy link
Author

Typescript version:

/**
 * wrap promise with error handler
 * @param {Promise} promise promise instance
 * @returns {Promise<[Error, Response]>}
 */
export function safeAwait<T>(promise: Promise<T>): Promise<[Error | null, T | null]> {
  return new Promise<[Error | null, T | null]>((resolve) => {
    promise
      .then((res) => {
        resolve([null, res])
      })
      .catch((e) => {
        resolve([e || new Error(), null])
      })
  })
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment