zoukankan      html  css  js  c++  java
  • 微信小程序异步请求问题

    微信小程序为了提高用户体验,提供的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/huangshuqiang/p/9156261.html(好物要分享,好的经验也需要分享^ ^)

  • 相关阅读:
    python多线程爬虫:亚马逊价格
    python在linux中输出带颜色的文字的方法
    单线程爬虫VS多线程爬虫的效率对比
    python爬虫:正则表达式
    爬虫-python调用百度API/requests
    Python gevent学习笔记-2
    Python gevent学习笔记
    IO多路复用之select总结
    select、poll、epoll之间的区别总结[整理]
    2020年 IEDA破解码失效,2019 版IDEA无法使用 ,已解决,有效期2100年;原标题:IDEA激活—免费永久激活(lookdiv.com)
  • 原文地址:https://www.cnblogs.com/dayin1/p/12179632.html
Copyright © 2011-2022 走看看