美文网首页异步回调
我在微信小程序使用generator方案解决异步回调的一点总结

我在微信小程序使用generator方案解决异步回调的一点总结

作者: 金逸凌云 | 来源:发表于2017-11-14 10:22 被阅读408次

    首先在使用前是参考了这位大神的文章:
    原文链接:http://www.jianshu.com/p/588f7e7f5555
    自己在实际npm install co regenerator --save 后发现文章中的js对应不到目前的版本了。
    现在实际的使用的是你装好后,进入node_modules,找到co中的index.js及regenerator 里的runtime.js,将这两个文件放入到小程序中。
    我放的路径在utils工具文件夹下。
    在utils文件夹下,首先新建一个fetch.js封装请求数据的接口

    // 封装请求接口
    function getApi(method, url, params={}){
      method = method.toUpperCase()
      var methodHeader = {}
      if(method == "POST"){
        methodHeader = { "content-type": "application/x-www-form-urlencoded" }
      } else if (method == "GET") {
        methodHeader = { 'content-type': 'application/json' }
      }
      return new Promise((resolve, reject) => {
        wx.request({
          url: url,
          method: 'GET',
          header: methodHeader,
          data: params,
          success: function (json) {
            resolve(json)
          },
          fail: function (json) {
            reject(json)
          }
        })
      })
     
    }
    
    module.exports = getApi
    
    

    为了在全局使用co和generator以及我自己封装的getApi.
    我在小程序的全局作用域,app.js中引入了

    const co = require('./utils/co.js')
    const regeneratorRuntime = global.regeneratorRuntime = require('./utils/runtime.js')
    const getApi = require('./utils/fetch.js')
    App({
      globalData: {
      },
      co: co,
      regeneratorRuntime: regeneratorRuntime,
      getApi: getApi,
      ...
    )}
    

    其实这里代码写的不够优雅,多少是有些冗余了。你可以自行修改。
    然后在请求接口的页面是这么用的:
    首先在顶部需要引入,不引入regeneratorRuntime会报错说regeneratorRuntime 找不到么。这个原因我没找到,估计是编译后的代码里直接需要使用全局变量regeneratorRuntime ,而小程序中全局变量需要用app.regeneratorRuntime 才能找到它。所以我重新赋值了一下。

    var app = getApp();
    var regeneratorRuntime = app.regeneratorRuntime; //这句是保证编译后的代码支持generator属性
    

    接下里在onLoad的生命周期里,请求接口:

    onLoad:function(options){
          app.co(function* () {
            try {
          //  这里是参数
              var params = {
                "typeCode": "blabla",
                "ocms_preview": 1111
              }
              var result = yield app.getApi('get', 'https://www.maijia.com/blabla', params);
          // result就是你请求到的数据,下面的操作根据自己的需求进行
              that.setData({
                "loaded": true,
                "auth_deny": app.globalData.auth_deny,
                'tags': result.data.data
              });
    
              //缓存数据tagData 
              wx.setStorage({
                key: 'tagData',
                data: result.data.data
              })
            } catch (e) {
              // console.log(e) 这里是接口请求失败的处理
              // 加载动画
              wx.showLoading({
                title: "加载失败",
              });
            }
          });
    }
    

    这样就可以在你的小程序里愉快的用generator来规避异步回调地狱了.

    相关文章

      网友评论

        本文标题:我在微信小程序使用generator方案解决异步回调的一点总结

        本文链接:https://www.haomeiwen.com/subject/evsxvxtx.html