wxPromise

将微信原生api封装为Promise形式使用

Source:

Members

(static, constant) wxPromise

Source:

小程序API的Promise封装,用法与wx一致,只是返回结果为Promise形式

Example
async func(){
     let imgInfo = await wxPromise.getImageInfo({src: 'https://xxx'}); //调用wx.getImageInfo,并在success回调中resolve
     console.log(imgInfo.width); //打印图片信息
 }

(static, constant) wxResolve

Source:

同wxPromise,差别在于wxPromise在成功时resolve,失败时reject,而wxResolve不管成功失败都会resolve,便于手动处理异常情形
会在返回结果中额外添加succeeded字段,用于区分成功失败

Example
async func(){
    let copyRes = await wxResolve.setClipboardData({ data: 'hello'});  //复制到剪贴板

    this.$toast({  //成功失败均予以提示
      title: copyRes.succeeded ? '复制成功' : '复制失败',
      type: copyRes.succeeded ? 'success' : 'fail',
    });
 }

Methods

(static) customWxPromisify(overrides, dealFail) → {Object}

Source:

自定义Promise化方式

Example
const wxPromise = customWxPromisify({
 overrides: { //部分api不直接使用wx,而是添加一些自定义逻辑
   navigateTo(options){
     console.log('custom navigateTo');
     wx.navigateTo(options);
   },
   request(options){
     console.log('custom request');
     wx.request(options);
   },
 },
 dealFail: false, //触发fail回调时,reject对应的Promise
});
let imgInfo = await wxPromise.getImageInfo({src: 'https://xxx'}); 
 console.log(imgInfo.width); //以Promise形式获取wx.getImageInfo返回结果

const wxResolve = customWxPromisify({
 overrides: { //部分api不直接使用wx,而是添加一些自定义逻辑
   navigateTo(options){
     console.log('custom navigateTo');
     wx.navigateTo(options);
   },
   request(options){
     console.log('custom request');
     wx.request(options);
   },
 },
 dealFail: true, //触发fail回调时,依然resolve对应的Promise,并在返回结果中添加succeeded字段标记成功失败
});
let copyRes = await wxResolve.setClipboardData({ data: 'hello'});
console.log(copyRes.succeeded ? '复制成功' : '复制失败'); //以Promise形式获取wx.setClipboardData返回结果,成功失败以succeeded字段区分
Parameters:
Name Type Description
overrides Object

自定义覆盖wx的部分接口

dealFail boolean

true - 失败时也resolve,并标记res.succeeded=false; false - 失败时直接reject

Returns:

Promise化的wx

Type
Object