【问题标题】:How to execute 2 function after one another in Typescript?如何在 Typescript 中依次执行 2 个函数?
【发布时间】:2021-04-02 13:51:19
【问题描述】:

我正在调用以下两个函数:

getStudentDataFunction(){
........
return studentData
}

getTeachersDataFunction(){
........
return teachersData
}

我希望 getTeachersDataFunction() 在之后执行 getStudentDataFunction() 完成返回数据。

有没有办法做到这一点?

【问题讨论】:

标签: javascript typescript


【解决方案1】:

同步和异步执行

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

getStudentDataFunction()
getTeachersDataFunction()

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

异步请求示例

这方面的一个例子是XMLHttpRequest,这是一种在浏览器中发出 HTTP 请求的标准方式(示例来自 Mozilla documentation):

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处理异步代码的一种方式对函数中的函数进行排序你想要的方式。三种主要方式是回调,Promisesasync functions(从最古老到最现代)。 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()

【讨论】:

    【解决方案2】:

    你可能需要用 Rxjs 使这两个方法 Observable,因此你可以这样做:

      caller() {
        this.method1()
          .pipe(switchMap(res1 => this.method2(res1)))
          .subscribe(res2 => {
            console.log(res2);
          });
      }
    

    另见演示:https://stackblitz.com/edit/angular-ivy-rn5kfe?file=src/app/app.component.ts

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-08
      • 2014-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-04
      • 2016-04-16
      • 1970-01-01
      相关资源
      最近更新 更多