如何在微信小程序中使用 Hprose(三)

Hprose 技術交流羣:48855729javascript

書接上回,上一回中咱們講到 Hprose 提供的協程可讓 Hprose 的異步調用同步化。可是在最後的例子中,有一個小的細節,不知道你有沒有注意到,就是程序的最後,咱們使用了這樣的代碼:java

this.setData({
      userInfo: yield app.getUserInfo
    });

將本來複雜的經過異步調用來設置 setData 的過程同步化了。這是由於 hprose 提供了的協程,能夠 yield 單參數回調方法的函數,並將回調方法的參數做爲該 yield 調用的返回值。從而避免了 thatthis 之間的轉換,也避免了寫回調函數。小程序

可是 hprose 的所提供對協程的支持不止於此,hprose 還將 wx 的全部 API 都封裝到了 hprose.wx 下面,將須要使用回調方式的 API 封裝成了返回 promise 對象的 API,經過這種封裝,全部這些 API,就均可以使用 co/yield 方式同步調用了。微信小程序

例如微信官方例子中,上傳文件的例子是這樣的:promise

wx.chooseImage({
  success: function(res) {
    var tempFilePaths = res.tempFilePaths
    wx.uploadFile({
      url: 'http://example.weixin.qq.com/upload', //僅爲示例,非真實的接口地址
      filePath: tempFilePaths[0],
      name: 'file',
      formData:{
        'user': 'test'
      },
      success: function(res){
        var data = res.data
        //do something
      }
    })
  }
})

如今換成 hprose 所提供的 API,就能夠變成這樣:微信

var hprose = require('../../utils/hprose.js');
var wx = hprose.wx;
var co = hprose.co;

co(function*() {
  var tempFilePaths = (yield wx.chooseImage()).tempFilePaths;
  var data = (yield wx.uploadFile({
    url: 'http://example.weixin.qq.com/upload', //僅爲示例,非真實的接口地址
    filePath: tempFilePaths[0],
    name: 'file',
    formData:{
      'user': 'test'
    }
  })).data;
  //do something
})

除去引入 hprose 的代碼之外,你會發現 co 程序段中的代碼,已經徹底變成了同步調用的寫法,避免了回調,讓程序變得更加簡單直觀和清晰了。app

再好比操做文件的例子:異步

wx.startRecord({
  success: function(res) {
    var tempFilePath = res.tempFilePath
    wx.saveFile({
      tempFilePath: tempFilePath,
      success: function(res) {
        var savedFilePath = res.savedFilePath
      }
    })
  }
})

轉化成同步代碼是這樣的:函數

var res = yield wx.startRecord();
var tempFilePath = res.tempFilePath;
res = yield wx.saveFile({ tempFilePath: tempFilePath });
var saveFilePath = res.savedFilePath;

沒有回調,沒有嵌套。整個程序就這麼清爽!ui

好了,我就很少舉例了,剩下的,我想你已經知道該怎麼作了。

相關文章
相關標籤/搜索