30秒学会 JavaScript 片段 · 2019年3月28日

30秒学会 JavaScript 片段 – promisify

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 => (...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