Files
30-seconds-of-code/snippets/js/s/promisify.md
Angelos Chalaris 4d0316a062 Update covers
2023-05-07 22:25:00 +03:00

789 B

title, type, language, tags, cover, dateModified
title type language tags cover dateModified
Promisify function snippet javascript
function
promise
nature-screen 2020-10-22T20:24:04+03:00

Converts an asynchronous function to return a promise.

  • Use currying to return a function returning a Promise that calls the original function.
  • Use the rest operator (...) to pass in all the parameters.
  • Note: In Node 8+, you can use util.promisify.
const promisify = func => (...args) =>
  new Promise((resolve, reject) =>
    func(...args, (err, result) => (err ? reject(err) : resolve(result)))
  );
const delay = promisify((d, cb) => setTimeout(cb, d));
delay(2000).then(() => console.log('Hi!')); // Promise resolves after 2s