promise.js 1.5 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
import {
  isFn
} from 'uni-shared'

const SYNC_API_RE = /hideKeyboard|upx2px|canIUse|^create|Sync$|Manager$/

const TASK_APIS = ['request', 'downloadFile', 'uploadFile', 'connectSocket']

const CALLBACK_API_RE = /^on/

export function isSyncApi (name) {
  return SYNC_API_RE.test(name)
}

export function isCallbackApi (name) {
  return CALLBACK_API_RE.test(name)
}

export function isTaskApi (name) {
  return TASK_APIS.indexOf(name) !== -1
}

function handlePromise (promise) {
  return promise.then(data => {
    return [null, data]
  })
    .catch(err => [err])
}

fxy060608's avatar
fxy060608 已提交
30
export function shouldPromise (name) {
fxy060608's avatar
fxy060608 已提交
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
  if (isSyncApi(name)) {
    return false
  }
  if (isCallbackApi(name)) {
    return false
  }
  return true
}

export function promisify (name, api) {
  if (!shouldPromise(name)) {
    return api
  }
  return function promiseApi (options = {}, ...params) {
    if (isFn(options.success) || isFn(options.fail) || isFn(options.complete)) {
      return api(options, ...params)
    }
    return handlePromise(new Promise((resolve, reject) => {
      api(Object.assign({}, options, {
        success: resolve,
        fail: reject
      }), ...params)
      /* eslint-disable no-extend-native */
      Promise.prototype.finally = function (callback) {
        const promise = this.constructor
        return this.then(
          value => promise.resolve(callback()).then(() => value),
          reason => promise.resolve(callback()).then(() => {
            throw reason
          })
        )
      }
    }))
  }
}