使用proxy 改写小程序接口为 promise

2019-10-09 15:25:10 浏览数 (1)

代码语言:javascript复制
const startsWith = (prefix, str) => str.startsWith(prefix)
const endsWith = (prefix, str) => str.endsWith(prefix)

const log = prefix => msg => console.log(`${prefix}: ${msg}`)

const _wx = new Proxy({}, {

  get(target, key, receiver){

    if(startsWith('on', key) || endsWith('Sync', key)  ){
      return wx[key]
    }

    return (args) => new Promise((reslove, reject) =>{
        wx[key](Object.assign({
          success: reslove,
          fail: reject
        }, args))
      
    })
  },

})


_wx.setStorage({
  key: 'token',
  data: '1111'
}).then(log('set success')).finally(() =>  _wx.removeStorageSync('token') )


_wx.showToast({
  title: 'msg',
  icon: 'success'
}).then(log('success')).catch(log('error')).finally(log('end'))

0 人点赞