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

fxy060608's avatar
fxy060608 已提交
5 6 7 8 9 10
import {
  invokeApi,
  wrapperReturnValue
} from './interceptor'

const SYNC_API_RE =
fxy060608's avatar
fxy060608 已提交
11
  /^\$|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/
fxy060608's avatar
fxy060608 已提交
12

13 14
const CONTEXT_API_RE = /^create|Manager$/

fxy060608's avatar
fxy060608 已提交
15 16 17 18
const TASK_APIS = ['request', 'downloadFile', 'uploadFile', 'connectSocket']

const CALLBACK_API_RE = /^on/

19 20 21
export function isContextApi (name) {
  return CONTEXT_API_RE.test(name)
}
fxy060608's avatar
fxy060608 已提交
22 23 24 25 26
export function isSyncApi (name) {
  return SYNC_API_RE.test(name)
}

export function isCallbackApi (name) {
fxy060608's avatar
fxy060608 已提交
27
  return CALLBACK_API_RE.test(name) && name !== 'onPush'
fxy060608's avatar
fxy060608 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40
}

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 已提交
41
export function shouldPromise (name) {
42 43
  if (
    isContextApi(name) ||
fxy060608's avatar
fxy060608 已提交
44 45
    isSyncApi(name) ||
    isCallbackApi(name)
46
  ) {
fxy060608's avatar
fxy060608 已提交
47 48 49 50 51 52 53 54 55 56 57
    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)) {
fxy060608's avatar
fxy060608 已提交
58
      return wrapperReturnValue(name, invokeApi(name, api, options, ...params))
fxy060608's avatar
fxy060608 已提交
59
    }
fxy060608's avatar
fxy060608 已提交
60 61
    return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => {
      invokeApi(name, api, Object.assign({}, options, {
fxy060608's avatar
fxy060608 已提交
62 63
        success: resolve,
        fail: reject
fxy060608's avatar
fxy060608 已提交
64
      }), ...params)
65 66 67 68 69 70 71 72 73 74 75
      /* eslint-disable no-extend-native */
      if (!Promise.prototype.finally) {
        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
            })
          )
        }
fxy060608's avatar
fxy060608 已提交
76
      }
fxy060608's avatar
fxy060608 已提交
77
    })))
fxy060608's avatar
fxy060608 已提交
78
  }
fxy060608's avatar
fxy060608 已提交
79
}