• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

js请求的同步和异步处理

武飞扬头像
luobinzi
帮助1

因为JavaScript的单线程,因此同个时间只能处理同个任务,所以任务的执行需要按排队方式一步一步的执行,但是当用户向后台获取大量的数据时,不得不等到所有数据都获取完毕才能进行下一步操作,这样会严重影响用户体验。

为解决这个问题,就需要用到异步,异步就相当与在一条跑道上好几个人一起出发,但其本质页还是一条跑道,与同步都是单线程。区别在于排队跑还是百米一起跑。

今天遇到一个关于同步异步的问题。

场景:uniapp中两个方法中,一个方法在data容器中存储数据,另一个方法引用data中的数据。两个方法都在onLoand中调用,导致调用的data数据为空。

  1.  
    //金刚区接口
  2.  
    async jingang() {
  3.  
    await getDistrict().then((res) => {
  4.  
    this.btn = res.result
  5.  
    //this.zoom()
  6.  
    console.log(this.btn, 3333333);
  7.  
    if (this.btn.length > 7) {
  8.  
    this.btnMin = this.btn.filter(num => num.dkey < 7 )
  9.  
    }
  10.  
    console.log(this.btnMin,3333);
  11.  
    })
  12.  
    // console.log(this.btn,0000000);
  13.  
    },
  14.  
    //跑马灯
  15.  
    getHorseRaceLamp(){
  16.  
    uni.request({
  17.  
     
  18.  
    url: 'http://192.168.3.80:9000/manager/user/getUserList',
  19.  
    data: {
  20.  
    // text: 'uni.request'
  21.  
    },
  22.  
    header: {
  23.  
    // 'custom-header': 'hello' //自定义请求头信息
  24.  
    },
  25.  
    success: (res) => {
  26.  
    this.lempList = res.data.result
  27.  
    // this.taskList = res.data.result
  28.  
    console.log(this.lempList, 123456);
  29.  
    }
  30.  
    });
  31.  
    },
  32.  
    zoom() {
  33.  
    console.log(this.btn, "woshixinde");
  34.  
    console.log(this.btn.length, 333);
  35.  
    // console.log(this.lempList,77777777);
  36.  
    if (this.btn.length > 7) {
  37.  
    // this.btnMin = arr.filter(num => num.dkey < 7 )
  38.  
    }
  39.  
     
  40.  
    console.log(this.btnMin, 11111122222);
  41.  
    },
学新通
  1.  
    onLoad() {
  2.  
    //调用金刚区接口
  3.  
    this.jingang()
  4.  
    //
  5.  
    this.getHorseRaceLamp()
  6.  
    this.zoom()
  7.  
    },

同步执行导致三个方法不确定谁先执行,导致方法zoom()可能会在方法jingang()的前面执行导致获取数据为空

学新通

正确解决:

将this.zoom调用zoom方法的语句写在获取数据方法jingang的方法体内

  1.  
    //金刚区接口
  2.  
    async jingang() {
  3.  
    await getDistrict().then((res) => {
  4.  
    this.btn = res.result
  5.  
    this.zoom()
  6.  
    console.log(this.btn, 3333333);
  7.  
    if (this.btn.length > 7) {
  8.  
    this.btnMin = this.btn.filter(num => num.dkey < 7 )
  9.  
    }
  10.  
    console.log(this.btnMin,3333);
  11.  
    })
  12.  
    // console.log(this.btn,0000000);
  13.  
    },

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhghakac
系列文章
更多 icon
同类精品
更多 icon
继续加载