我有3个函数,我想一个接一个地调用
openTryFunction(){
// function one
this.functionOne();
// after function one
this.functionTwo();
// after function two
this.functionTree(); }
答案 0 :(得分:8)
因此,您具有三个功能functionOne
,functionTwo
和functionThree
。可以有多个PnC来确定这些功能是同步还是异步。
让我们将这些场景概括为两个主要类别:
所有操作都是同步的:如果是这种情况,则您的代码将一个接一个地运行(同步)。
如果任何函数是异步的:如果是这种情况,则本质上是异步的函数应让应该在此之后调用的函数知道它已经终止了。在这种情况下,您可以从该异步函数返回Promise / Observable。或者,您可以向其传递一个回调函数,该函数将在异步函数完成执行后被调用。
这是两个示例:
那你应该这样写:
openTryFunction() {
this.functionOne()
.subscribe(
() => this.functionTwo()
.subscribe(() => this.functionThree()
.subscribe(() => console.log('Function three terminated')))
);
}
functionOne
和functionTwo
返回了承诺,则:
openTryFunction() {
this.functionOne().then(() => {
this.functionTwo().then(() => this.functionThree());
});
}
更新:
您还可以使用async
和await
来获得更简洁的代码。这是一个简单但具体的例子:
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
users;
constructor(private http: HttpClient) {}
ngOnInit() {
this.getAllData();
}
getUsers() {
return this.http.get('https://jsonplaceholder.typicode.com/users')
.toPromise();
}
getUserPosts(userId) {
return this.http.get(`https://jsonplaceholder.typicode.com/posts?userId=${userId}`)
.toPromise();
}
getPostComments(postId) {
return this.http.get(`https://jsonplaceholder.typicode.com/comments?postId=${postId}`)
.toPromise();
}
async getAllData() {
const users = await this.getUsers();
const posts = await this.getUserPosts(users[0].id);
const comments = await this.getPostComments(posts[0].id);
console.log(users);
console.log(posts);
console.log(comments);
}
}
这里是StackBlitz。
希望如此。
答案 1 :(得分:3)
您可以使用Promise:
functionOne(): Promise<any> {
return Promise.resolve((() => {
// code here
return 'from first'; // return whatever you want not neccessory
})());
}
functionTwo(): Promise<any> {
return Promise.resolve((() => {
// code here
return 'from second'; // return whatever you want not neccessory
})());
}
functionThree() {
// code here
}
this.functionOne().then(data1 => {
console.log(data1);
this.functionTwo().then(data2 => {
console.log(data2);
this.functionThree();
});
});
答案 2 :(得分:3)
如果您的函数是同步的,那么您在做什么就可以了。如果它们是异步的并且返回了promise,则可以将它们按以下方式串在一起:
fOne()
.then(() => {
fTwo()
} ).then(() => {
fThree()
});
或者,您可以使用异步等待。
async function tasks() {
await fOne();
await fTwo();
await fThree();
}
请确保我们尝试使用catch来处理异常。
如果您的函数返回可观察值,那么concatMap是您的朋友。
fOne()
.concatMap(() => fTwo())
.concatMap(() => fThree());
给出您的最后一个函数如果您使用异步等待,则不返回承诺,您可以在上一次调用中省略等待。
答案 3 :(得分:1)
如果函数返回一个可观察值,则只需在 subscribe
中调用下一个函数。否则,从每个函数返回一个承诺。然后,您可以链接调用的函数。
functionOne() {
return new Promise((resolve) => {
//
// Your function implementation
//
// Resolve the promise at the end
resolve();
});
}
functionTwo() {
return new Promise((resolve) => {
//
// Your function implementation
//
// Resolve the promise at the end
resolve();
});
}
functionThree() {
return new Promise((resolve) => {
//
// Your function implementation
//
// Resolve the promise at the end
resolve();
});
}
openTryFunction(){
// function one
this.functionOne().then(() => {
// after function one
this.functionTwo().then(() => {
// after function two
this.functionTree();
});
});
}
答案 4 :(得分:1)
请看此示例,其中每个函数返回一个Observable
,执行顺序由一个concat
函数控制。
export class AppComponent implements OnInit {
name = 'Angular';
values = [];
first(): Observable<string> {
return of('first');
}
second(): Observable<string> {
return of('second');
}
afterSecond(): Observable<string> {
return of('secondish');
}
third(): Observable<string> {
return of('third');
}
ngOnInit() {
let sequence = concat([
this.first,
this.second,
this.afterSecond,
this.third]);
sequence.subscribe(currentFunction => {
currentFunction().subscribe(value => {
this.values.push(value);
})
});
}
}
我喜欢concat
函数,因为它建立了我们添加到列表中的函数Observable
。
请注意,此调用sequence.subscribe(currentFunction
currentFunction
中的每个值都是一个函数,并且为了获得其实际值,因为它是Observable
,因此您需要订阅它。
请在此处查看完整的示例:https://stackblitz.com/edit/angular-functions-in-sequence?file=src%2Fapp%2Fapp.component.ts
答案 5 :(得分:0)
您可以尝试一下
openTryFunction(){
this.functionOne().then(()=>{this.functionTwo().then(() => {this.functionTree()})})}
功能3将在2完成后运行,而2将在1完成后运行。