转换一个异步函数,以返回一个 promise 。
使用柯里化返回一个函数,这个函数返回一个调用原始函数的 Promise
。 使用 ...rest
运算符传入所有参数。
在 Node 8+ 中,你可以使用
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
更多代码 JavaScript 实用代码片段 请查看 https://www.7psus5.com/30-seconds-of-code/
最新评论
写的挺好的
有没有兴趣翻译 impatient js? https://exploringjs.com/impatient-js/index.html
Flexbox playground is so great!
感谢总结。
awesome!
这个好像很早就看到类似的文章了
比其他的教程好太多了
柯理化讲的好模糊…没懂