promisify [承诺]
转换异步 功能以返回承诺。
In Node 8+, you can use util.promisify
使用 currying 返回函数返回 Promise
该调用原始功能。
使用 ...rest
运算符传递所有参数。
typescript
const promisify =
(func: Function) =>
(...args: any[]) =>
new Promise((resolve, reject) =>
func(...args, (err: Error, result: any) =>
err ? reject(err) : resolve(result)
)
);
typescript
const delay = promisify((d, cb) => setTimeout(cb, d));
delay(2000).then(() => console.log("Hi!")); // // Promise resolves after 2s