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

      })
相关推荐
Insseals19 分钟前
因斯特浮动模块快速接头✨五大核心优势
前端
沐土Arvin35 分钟前
港澳台行政区域json
前端
程序员鱼皮1 小时前
我花 300 块,让 Claude Fable 5 开发桌面 APP,值么?
前端
William_Xu1 小时前
JavaScript 并发控制
前端
拾年2751 小时前
从零手写 Ajax:用原生 XHR 搭建前后端交互全流程
前端·javascript·ajax
光影少年1 小时前
懒加载与分包:React.lazy + Suspense
前端·react.js·掘金·金石计划
拉勾科研工作室1 小时前
区块链工程毕业论文题目【249个】
开发语言·javascript
小林ixn1 小时前
你以为你懂 + 号?看完这篇 Bun + TS 实战,才发现以前全写错了
前端·javascript·typescript
namexingyun2 小时前
开源前端生态如何成为 AI UI 生成的“燃料“:shadcn/ui、Tailwind CSS、Storybook 技术价值全解剖
java·前端·人工智能·python·ui·开源·ai编程
Zyed2 小时前
[STM32]Day15读写FLASH+读取ID
前端·stm32·性能优化