wepy

wepy开启使用promise

在app.wpy中使API promise化

export default class extends wepy.app {

    constructor () {
        super();
        this.use('promisify');
    }

}

使用:没加promise之前,res的值undefined

    async requestUrl() {
      let self = this;
      let time = util.getCurrentTime();
      let key = 'www.mall.cycle.com';
      let sign = md5.hex_md5((time + key).toLowerCase());
      let data = { sign: sign, time: time, page: 1, size: 10 };
      let url = 'http://api-mall.dyq086.cn/emall/api/mall/discoverList';
      let res = await wepy.request({
        url: url,
        method: 'GET',
        data: data,
        header: { 'Content-Type': 'application/json' },
        // success: function(res) {
        //   console.warn(res);
        //   return res;
        // }
      });
      console.warn('res=');
      console.warn(res);
    },

分析:

promise基本请求网络数据

    //注意:使用了promise,success回调方法无效

    requestBaseUrl() {
      let self = this;
      let url =
        'https://www.madcoder.cn/tests/sleep.php?time=1&t=css&c=MA==&i=9';
      wepy
        .request({
          url: url,
          method: 'GET',
          // success: function(res) {
          //   console.warn(res);
          //   return res;
          // }
        })
        .then(d => console.log(d));
    },

async-await-网络请求

  async requestBaseUrlAwait() {
    let self = this;
    let url = 'https://www.madcoder.cn/tests/sleep.php?time=1&t=css&c=MA==&i=9';
    let res = await wepy.request({
      url: url,
      method: 'GET'
    });
    console.warn(res.data);
    return res;
  }
  //结果
  //0

 

async-await-没有resolve结果的情况

 // pomise对象
  async f1() {
    let self = this;
    await new Promise(resolve => {
      console.log(1);
    });
    console.log(2);
  }

  testAwaitNotReturn() {
    let self = this;
    self.f1();
    console.log(3);
  }
  //结果
  //2
  //3

 async-await-有resolve结果的情况

  async f2() {
    let self = this;
    await new Promise(resolve => {
      console.log(1);
      resolve();
    });
    console.log(2);
  }

  testAwaitReturn() {
    let self = this;
    self.f2();
    console.log(3);
  }
  //结果
  //2
  //3
  //1

wepy例子

效果:

wepy_第1张图片

代码:





 

你可能感兴趣的:(微信小程序)