promise.js 948 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import { asyncMethods } from './method'
  2. function hasCallback(args) {
  3. if (!args || typeof args !== 'object') return false
  4. const callback = ['success', 'fail', 'complete']
  5. for (const m of callback) {
  6. if (typeof args[m] === 'function') return true
  7. }
  8. return false
  9. }
  10. function _promisify(func) {
  11. if (typeof func !== 'function') return fn
  12. return (args = {}) =>
  13. new Promise((resolve, reject) => {
  14. func(
  15. Object.assign(args, {
  16. success: resolve,
  17. fail: reject
  18. })
  19. )
  20. })
  21. }
  22. export function promisifyAll(wx = {}, wxp = {}) {
  23. Object.keys(wx).forEach(key => {
  24. const fn = wx[key]
  25. if (typeof fn === 'function' && asyncMethods.indexOf(key) >= 0) {
  26. wxp[key] = args => {
  27. if (hasCallback(args)) {
  28. fn(args)
  29. } else {
  30. return _promisify(fn)(args)
  31. }
  32. }
  33. } else {
  34. wxp[key] = fn
  35. }
  36. })
  37. }
  38. export const promisify = _promisify