• 微信小程序异步请求问题


    微信小程序为了提高用户体验,提供的api大部分都是异步操作,除了数据缓存操作里面有一些同步操作。是提高了用户体验,但是在开发的时候,

    就有点坑了,例如我要写一个公共方法,发起网络请求,去后台去一些数据,成功之后,再做一些操作,但是由于wx.request是异步请求,就会

    导致,网络请求还没结束,就会执行后面的代码,从而引起异常,怎么解决这种异步导致的问题呢,当然是promise了。看例子:

    公共common.js里封装了一个得到用户实体的方法:

    //发起请求,得到用户实体
    function GetUserEntity() {
      wx.request({
        url: http_config.getUserDetail,
        data: {
          Sha1OpenId: wx.getStorageSync('LoginSessionKey')
        },
        success: (res) => {
          let result = res.data.data;
          console.log(result)
          return result;
        },
        fail: () => {
          return "系统异常,请重试!"
        }
      })
    }
    module.exports.GetUserEntity = GetUserEntity
    

      然后在另一个js中调用这个方法,得到用户实体成功之后,在进行一系列操作:

    const com = require(`${root_path}/utils/common.js`)
    //在方法中进行一下操作
    
        let userEntity = com.GetUserEntity();
        console.log(userEntity.Sex)
        console.log("得到实体之后进行的操作")
    

     执行之后会发现,程序报错

    明明实体用有Sex这个属性,为什么报错,这就是异步请求造成的问题,请求还没返回值,下面的代码已经执行了。

    解决办法:利用promise

    网络请求改成:

    function GetUserEntity() {
      return new Promise(function (resolve, reject) { 
        wx.request({
          url: http_config.getUserDetail,
          data: {
            Sha1OpenId: wx.getStorageSync('LoginSessionKey')
          },
          success: (res) => {
            let result = res.data.data;
            resolve(result) ;
          },
          fail:()=>{
            reject("系统异常,请重试!")
          }
        })
      })
      
    }
    

     请求方法改成:

    comm.GetUserEntity().then((res) => { console.log(res) }).catch((res) => { console.log(res) })
    

     简单记忆:resolve 返回,之后代码走then,reject返回,那么代码就会走catch。

    我们可以把执行GetUserEntity方法之后要执行的代码放在then中,如果GetUserEntity中发起的请求出错那么程序就会通过reject返回信息,

    那么我们可以再catch中做相应的处理。

    参考:https://www.cnblogs.com/zhihuama/articles/9143954.html

              https://blog.csdn.net/qq_32786873/article/details/72179601

  • 相关阅读:
    zabbix监控系统客户端安装
    可以学习的博客地址
    Linux下Nagios的安装与配置
    ShopNC多用户商城标题去版权 后台去版权方法2.0版本
    解析crontab php自动运行的方法
    暑假周报告(第五周)
    暑假周报告(第四周)
    暑假周报告(第三周)
    暑假周报告(第二周)
    《大道至简》读后感
  • 原文地址:https://www.cnblogs.com/huangshuqiang/p/9156261.html
Copyright © 2020-2023  润新知