vue请求如何按顺序执行

我们有时候会碰到这种情况,需要连续发送两个请求,第二个请求需要用第一个请求的某个返回值作为参数来作为第二个请求的请求参数。

但是存在一个问题:两个请求都是异步的,他并不按照我们期望的先后顺序来执行。

这时候就需要控制请求的执行顺序,这里我提供一种方法来实现请求的顺序控制,我认为这个方法写起来是最简单最容易理解的。(当然其他方法有很多,还有async和await关键字等)

书写格式:

首先是正常发送第一次请求,然后在第一次请求的回调函数then中,写一句return 来发送第二次请求。

再.then,这里的返回结果就是第二次请求的结果。

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

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

实际使用示例:

js 复制代码
      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;
        }

      })
相关推荐
前端 贾公子2 分钟前
ElementUI 中 validateField 对部分表单字段数组进行校验时多次回调问题
前端·javascript·elementui
棒棒的唐3 分钟前
vue2 elementUI 登录页面实现回车提交登录的方法
前端·javascript·elementui
前端小万6 分钟前
一次紧急的现场性能问题排查
前端·性能优化
zhangzuying10266 分钟前
基于Vue3 +ElementuiPlus + Dexie.js自研的浏览器插件新建标签页tab
vue.js·typescript·echarts
lichong95112 分钟前
【混合开发】vue+Android、iPhone、鸿蒙、win、macOS、Linux之video 的各种状态和生命周期调用说明
android·vue.js·macos
excel21 分钟前
为什么相同卷积代码在不同层学到的特征完全不同——基于 tfjs-node 猫图像识别示例的逐层解析
前端
知识分享小能手22 分钟前
React学习教程,从入门到精通,React 使用属性(Props)创建组件语法知识点与案例详解(15)
前端·javascript·vue.js·学习·react.js·前端框架·vue
用户214118326360224 分钟前
dify案例分享-免费玩转即梦 4.0 多图生成!Dify 工作流从搭建到使用全攻略,附案例效果
前端
CodeSheep24 分钟前
稚晖君又开始摇人了,有点猛啊!
前端·后端·程序员
JarvanMo27 分钟前
Flutter Web vs Mobile:主要区别以及如何调整你的UI
前端