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;
        }

      })
相关推荐
志尊宝6 小时前
Vue3 零基础每日笔记(052):路由常见坑一次排雷——404、刷新丢参数、部署白屏
前端·javascript·vue.js·笔记·html5
linux_cfan6 小时前
videojs v10 源代码系列解读:13 · 能力型媒体契约:`Media` 的组合接口
前端·javascript·音视频
涛涛ing6 小时前
2026年9月,前端圈同时发生了四件事,指向同一个方向
前端
艾伦野鸽ggg7 小时前
Vue2 模板语法与样式绑定
前端
Amos_Web7 小时前
Rspack 源码解析(十一):资产 Hook 与增量构建
前端·rust·源码阅读
PC2005_cloud7 小时前
Windows 数据使用量页面卡死:1097 个热点档案和 161 MB 的 SRUM 库
前端·后端
烈风逍遥7 小时前
AI大模型中fetch 和 ReadableStream为啥一起出现
前端·人工智能
雪芽蓝域zzs7 小时前
第 11 章:封装通用 BaseEchart 基础图表组件(Vue3 + 若依,全局复用)
vue.js·echars
PC2005_cloud7 小时前
Nginx 防盗链配置实战:用 referer 模块保护网站静态资源
前端·后端
福兮说7 小时前
Canvas 文字排版:measureText 量出来的宽度为什么总是不对
前端·javascript