promise.js 1.7 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4
import {
  isFn
} from 'uni-shared'

fxy060608's avatar
fxy060608 已提交
5
const SYNC_API_RE = /requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$/
fxy060608's avatar
fxy060608 已提交
6

7 8
const CONTEXT_API_RE = /^create|Manager$/

fxy060608's avatar
fxy060608 已提交
9 10 11 12
const TASK_APIS = ['request', 'downloadFile', 'uploadFile', 'connectSocket']

const CALLBACK_API_RE = /^on/

13 14 15
export function isContextApi (name) {
  return CONTEXT_API_RE.test(name)
}
fxy060608's avatar
fxy060608 已提交
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
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 已提交
35
export function shouldPromise (name) {
fxy060608's avatar
fxy060608 已提交
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 66 67 68 69 70
  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
          })
        )
      }
    }))
  }
}