Skip to main content
File

title: promisify tags: function,promise,intermediate

TS JS Deno

Converts an asynchronous function to return a promise.

In Node 8+, you can use util.promisify

Use currying to return a function returning a Promise that calls the original function. Use the ...rest operator to pass in all the parameters.

const promisify = (func: Function) => (...args: any[]) =>
  new Promise((resolve, reject) =>
    func(...args, (err: Error, result: any) =>
      err ? reject(err) : resolve(result)
    )
  );
const delay = promisify((d, cb) => setTimeout(cb, d));
delay(2000).then(() => console.log("Hi!")); // // Promise resolves after 2s