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

      })
相关推荐
anyup20 分钟前
2027 年初,uni-app 官方停更,老项目该何去何从?
前端·vue.js·uni-app
KooFE26 分钟前
AI 重塑研发体系,从技能驱动到意图驱动
前端·ai编程
枣把儿30 分钟前
剪贴板、截图标注、长截图、自动运镜录屏,我全塞进一个不到 3MB 的免费开源软件里
前端·macos·swiftui
圆心角31 分钟前
AI 前端面试:失败重试、知识库、MCP 和大文档,问到多深
前端·面试·ai编程
徐小夕34 分钟前
JitKnow 5.0发布:让AI知识库变成可组装的知识中台
前端·vue.js·github
圆心角37 分钟前
2026 前端面试:拆完 11 篇 AI 面经,这 10 个方向必考
前端·面试·ai编程
dadaobusi39 分钟前
学习:noc死锁
java·服务器·前端
*Snowgrass*43 分钟前
npm简要介绍
前端·npm·node.js
斯内普吖1 小时前
(开源)校园资料分享平台实战指南 基于 Node.js + Express + Vue + MySQL
vue.js·mysql·开源·node.js·express
妮妮分享1 小时前
定位坐标偏移几百米?GCJ-02 / WGS84 / BD-09 坐标系踩坑实录(JS 附代码)
开发语言·javascript·坐标系转换·wgs84·gcj02