gpt4 book ai didi

typescript 中带有 Promise 的 Angular 调用函数

转载 作者:行者123 更新时间:2023-12-02 20:15:27 25 4
gpt4 key购买 nike

我有3个功能。我想在一个函数完成后调用另一个函数。在我的第一个函数中,我在页面中设置一个变量(学生)。第二个函数使用该变量。所以我正在使用 promise 。但我尝试了很多方法。但我无法用 promise 执行代码。我希望,在我的 ButtonClick 中,我的三个函数应该异步有序工作。我想要像下面这样的。我能怎么做?

  students: [];
studentInfoList: [];
otherList: [];

buttonClick() {
const myPromise = new Promise(function (resolve, reject) {
myFirstOperation();
});

myPromise()
.then(result => {
mySecondOperation();
})
.then(result => {
myThirdOperation();
});
}


myFirstOperation() {
this.studentService.getStudents().subscribe(
result => {
this.students = result.data;
});
}

mySecondOperation() {
for (let student of this.students) {
this.studentInfoList.push({ studenNameSurname=student.Name + student.Surname });
}
}

myThirdOperation() {
for (let studentInfo of this.studentInfoList) {
this.otherList.push(this.studentInfoList);
}
}

最佳答案

试试这个方法。

student = [];
studentInfoList = [];
otherList = [];

this.buttonClick().then(() => {
this.buttonClickResult().then((data) => {
this.secondFunction().then(() => {
this.thiedFunction();
});
});
})

buttonClick(){
return new promise((resolve , reject) => {
// Do your stuff hear
})
}

buttonClickResult(){
return new promise((resolve , reject) => {
this.studentService.getStudents().subscribe((result) => {
this.student.push(...result.data);
resolve("pass data hear"); // Pass data if you need.
})
})
}

secondFunction(){
return new promise((resolve , reject) => {
for (let data of this.student) {
this.studentInfoList.push({ "studenNameSurname" : data.Name + data.Surname });
}
})
}

thiedFunction(){
this.otherList.push(...this.studentInfoList);
}

关于 typescript 中带有 Promise 的 Angular 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52533350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com