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

5
const SYNC_API_RE = /^\$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/
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) {
36 37 38
  if (
    isContextApi(name) ||
        isSyncApi(name) ||
fxy060608's avatar
fxy060608 已提交
39
        isCallbackApi(name)
40
  ) {
fxy060608's avatar
fxy060608 已提交
41 42 43 44 45 46 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)) {
      return api(options, ...params)
    }
    return handlePromise(new Promise((resolve, reject) => {
      api(Object.assign({}, options, {
        success: resolve,
        fail: reject
fxy060608's avatar
fxy060608 已提交
58
      }), ...params)
59 60 61 62 63 64 65 66 67 68 69
      /* 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 已提交
70
      }
fxy060608's avatar
fxy060608 已提交
71 72
    }))
  }
73
}