vue请求如何按顺序执行

我们有时候会碰到这种情况,需要连续发送两个请求,第二个请求需要用第一个请求的某个返回值作为参数来作为第二个请求的请求参数。
但是存在一个问题:两个请求都是异步的,他并不按照我们期望的先后顺序来执行。
这时候就需要控制请求的执行顺序,这里我提供一种方法来实现请求的顺序控制,我认为这个方法写起来是最简单最容易理解的。(当然其他方法有很多,还有async和await关键字等)

书写格式:
首先是正常发送第一次请求,然后在第一次请求的回调函数then中,写一句return 来发送第二次请求。
再.then,这里的返回结果就是第二次请求的结果。

这样我们就实现了两个请求的顺序执行。

      first().then(response1 => {
        //第一次请求
        this.form = response1.data;
        console.log("第一次请求")
        //发送第二次请求
        return second(this.form.Code);
      }).then(response2 => {
      	console.log("第二次请求")
        //处理第二次请求返回结果
        this.queryParams=response2.data
      })

实际使用示例:

      getLastDataByUnifiedNumber(this.form.unifiedNumber).then(response1 => {
        //第一次请求查询采样表数据
        this.form = response1.data;
        this.form.address = this.form.provinceName + this.form.cityName + this.form.countyName;
        this.queryParams=this.form;
        return getListBySamplingCode(this.form.samplingCode);

      }).then(response2 => {
        //第二次请求查询测试结果数据
        this.form2 = response2.rows[0];
        if(this.form2){
          this.queryParams.alkaliHydrolyzedNitrogenFirst=this.form2.alkaliHydrolyzedNitrogenFirst;
          this.queryParams.availablePhosphorusFirst=this.form2.availablePhosphorusFirst;
          this.queryParams.availableKFirst=this.form2.availableKFirst;
          this.queryParams.organicMatterFirst=this.form2.organicMatterFirst;
        }

      })
  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

丿BAIKAL巛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值