JS回调(callback)Promise化

in 前端 with 0 comment

在看https://github.com/wechat-miniprogram/miniprogram-api-promise,微信小程序的api,promise化。

记录一下核心代码

function hasCallback (args) {
  if (!args || typeof args !== 'object') return false

  const callback = ['success', 'fail', 'complete']
  for (const m of callback) {
    if (typeof args[m] === 'function') return true
  }
  return false
}

function _promisify (func) {
  return (args = {}) =>
    new Promise((resolve, reject) => {
      func(
        Object.assign(args, {
          success: resolve,
          fail: reject
        })
      )
    })
}

export function promisify (fn) {
  if (typeof fn === 'function') {
    return args => {
      if (hasCallback(args)) {
        fn(args)
      } else {
        return _promisify(fn)(args)
      }
    }
  } else {
    return fn
  }
}
Comments are closed.