blog icon indicating copy to clipboard operation
blog copied to clipboard

如何让你的回调 Promise 化

Open huruji opened this issue 6 years ago • 0 comments

1523802758640.jpg 虽然现在是 9102 年了,但是不得不面对的现实是仍然有大量的老旧的采用回调的方式的函数,如果你在业务开发中受不了了,那么就可以考虑一下 Promise 化你的 callback 调用

其实我们仔细想想,最简陋的方式就是用一个 Promise 包装一下,将 resolve 替换为 callback 传给原函数就可以了,如下:

const promisify = (fn) => (...args) => new Promise((resolve, reject) => {
        args.push(resolve)
        fn.apply(this, args)
    })

测试一下

const testCb = function (a, b, callback) {
    setTimeout(() => {
        callback(a + b)
    }, 1000)
}

promisify(testCb)(10, 12)
    .then(data => {
        console.log(data)
    })

或许你的函数设计者受 Node.js api 的影响,会将 error 对象作为 callback 的第一个参数,那么我们只需要将 error reject 就可以了

const promisify = (fn) => (...args) => new Promise((resolve, reject) => {
    args.push((err, ...result) => {
        if (err) reject(err)
        else resolve.apply(this, result)
    })
    fn.apply(this, args)
})

是的,将你的 callback 回调 Promise 化就是这么简单,赶紧用起来吧。

huruji avatar Jan 19 '19 16:01 huruji