Skip to content

Instantly share code, notes, and snippets.

@burdiuz
Last active October 31, 2021 22:01
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 burdiuz/7b31f96827c4e5a070ec90be3f2e0572 to your computer and use it in GitHub Desktop.
Save burdiuz/7b31f96827c4e5a070ec90be3f2e0572 to your computer and use it in GitHub Desktop.
Function that runs in Promise.race() your promise and a timeout, if timeout completes first, resulting promise rejects with error.

@actualwave/resolve-or-timeout

Function that runs in Promise.race() your promise and a timeout, if timeout completes first, resulting promise rejects with error.

export const resolveOrTimeout = <T = unknown>(
  
  // Promise or a function that will be passed to a Promise object
  promiseOrHandler:
    | Promise<T>
    | ((
        resolve: (data: T) => void,
        reject?: (data: unknown) => void
      ) => unknown),
        
  // timeout in milliseconds. if 0, race condition will not apply and original promise will be returned as is
  timeout: number, 
    
  // optional, timeout error message
  timeoutError?: string, 
  
  // optional callback that will be executed when timeout completes first
  onTimeout?: (msg: string) => void 
) => Promise<T>;

Example

try {
  /*
    if request resolves in less than 500 ms, you will get response
  */
  const response = await resolveOrTimeout(
    fetch('/super/long/request'),
    500,
    'Sorry, your request takes toooooo long.',
  );
} catch (error) {
  /*
    if request takes longer than 500 ms, promise rejects with error message
  */
}

It accepts promise or a function that will be passed to a promise.

const response = await resolveOrTimeout(
  (resolve) => {
    // do something then resolve
  },
  500
);
export declare const resolveOrTimeout = <T = unknown>(
promiseOrHandler:
| Promise<T>
| ((
resolve: (data: T) => void,
reject?: (data: unknown) => void
) => unknown),
timeout: number,
timeoutError?: string,
onTimeout?: (msg: string) => void
) => Promise<T>;
export default resolveOrTimeout;
export const resolveOrTimeout = (
promiseOrHandler,
timeout,
timeoutError = `Async operation didn't complete in ${timeout}ms.`,
onTimeout
) => {
const promise =
typeof promiseOrHandler === 'function' ? new Promise(promiseOrHandler) : promiseOrHandler;
return timeout
? Promise.race([
promise,
new Promise((_, rej) =>
setTimeout(() => {
rej(timeoutError);
onTimeout && onTimeout(timeoutError);
}, timeout)
),
])
: promise;
};
export const resolveOrTimeout = <T = unknown>(
promiseOrHandler:
| Promise<T>
| ((
resolve: (data: T) => void,
reject?: (data: unknown) => void
) => unknown),
timeout: number,
timeoutError = `Async operation didn't complete in ${timeout}ms.`,
onTimeout?: (msg: string) => void
): Promise<T> => {
const promise =
typeof promiseOrHandler === 'function' ? new Promise<T>(promiseOrHandler) : promiseOrHandler;
return timeout
? Promise.race<Promise<T>>([
promise,
new Promise((_, rej) =>
setTimeout(() => {
rej(timeoutError);
onTimeout && onTimeout(timeoutError);
}, timeout)
),
])
: promise;
};
{
"name": "@actualwave/resolve-or-timeout",
"version": "0.0.1",
"description": "Function that runs in Promise.race() your promise and a timeout, if timeout completes first resulting promise rejects with error.",
"main": "resolve-or-timeout.js",
"module": "index.js",
"types": "index.d.ts",
"keywords": [
"Promise",
"race",
"timeout"
],
"homepage": "https://gist.github.com/burdiuz/7b31f96827c4e5a070ec90be3f2e0572",
"bugs": {
"url": "https://gist.github.com/burdiuz/7b31f96827c4e5a070ec90be3f2e0572",
"email": "burdiuz@gmail.com"
},
"license": "MIT",
"author": "Oleg Galaburda <burdiuz@gmail.com> (http://actualwave.com/)"
}
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const resolveOrTimeout = (
promiseOrHandler,
timeout,
timeoutError = `Async operation didn't complete in ${timeout}ms.`,
onTimeout
) => {
const promise =
typeof promiseOrHandler === 'function' ? new Promise(promiseOrHandler) : promiseOrHandler;
return timeout
? Promise.race([
promise,
new Promise((_, rej) =>
setTimeout(() => {
rej(timeoutError);
onTimeout && onTimeout(timeoutError);
}, timeout)
),
])
: promise;
};
exports.resolveOrTimeout = resolveOrTimeout;
exports.default = resolveOrTimeout;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment