为了账号安全,请及时绑定邮箱和手机立即绑定

如何在Typescript中依次执行2个函数?

如何在Typescript中依次执行2个函数?

慕虎7371278 2024-01-18 09:46:36
我正在调用以下两个函数:getStudentDataFunction(){........return studentData}getTeachersDataFunction(){........return teachersData}我希望 getTeachersDataFunction() 在 getStudentDataFunction() 完成返回数据后执行。有没有办法做到这一点?
查看完整描述

2 回答

?
汪汪一只猫

TA贡献1898条经验 获得超8个赞

同步和异步执行

如果函数是同步的,则可以按顺序调用它们,因为它们是一个接一个执行的:

getStudentDataFunction()
getTeachersDataFunction()

然而,这些函数大概是异步的,否则你就不会问这个问题。这意味着该函数中的一条语句必须启动获取数据的过程,但它是通过另一程序路径获取的。

异步请求示例

一个例子是XMLHttpRequest,发出浏览器内 HTTP 请求的标准方法(该示例来自Mozilla 文档):

var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "http://www.example.org/example.txt");
oReq.send();

这里oReq.send();发出HTTP请求,开始请求数据的过程。但实际获取数据的方式是通过使用reqListener第二行中的回调函数。当数据准备好时,将使用this上下文对象单独调用该函数,该上下文对象允许获取 HTTP 响应。因此,任何因 HTTP 请求返回而执行的代码都必须从 调用reqListener

适用于您的场景

为了让您的函数按顺序运行,您需要识别回调函数或getStudentDataFunction()用于获取其数据的其他机制,然后使用 JavaScript 处理异步代码的方法之一以您想要的方式对函数进行排序。三种主要方式是回调、Promises和异步函数(从最古老到最现代)。getStudentDataFunction()本身应该使用这三种方法之一。

这些将按如下方式工作:

// 1. If getStudentDataFunction() accepts a callback


var studentCallback = function(studentData) {

   getTeachersDataFunction()

}

getStudentDataFunction(studentCallback)


// 2. If getStudentDataFunction() returns a Promise:


getStudentDataFunction()

   .then(getTeachersDataFunction) // second function is only called when Promise resolves


// 3. If getStudentDataFunction() returns a Promise and you wish to use async functions:


async function getAllData() {

   await getStudentDataFunction() // await keyword makes execution wait for Promise to resolve

   getTeachersDataFunction()

}


getAllData()


查看完整回答
反对 回复 2024-01-18
?
慕沐林林

TA贡献2016条经验 获得超9个赞

您可能需要使用 Rxjs 使这两个方法可观察,因此您可以执行以下操作:


  caller() {

    this.method1()

      .pipe(switchMap(res1 => this.method2(res1)))

      .subscribe(res2 => {

        console.log(res2);

      });

  }

查看完整回答
反对 回复 2024-01-18
  • 2 回答
  • 0 关注
  • 29 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信