如何处理异步操作
在 typescript 中,我们有多种方法来处理异步操作:回调、promise 和 async/await。异步编程使我们能够管理可能需要时间的操作,例如从 api 获取数据,而不会阻塞其他代码的执行。
回调
回调是作为参数传递给另一个函数的函数,并在任务完成后执行。虽然回调适用于简单的任务,但当需要链接操作时,它们很快就会变得不可读。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
type todo = {
id: number;
userid: number;
title: string;
completed: boolean;
};
const createpromise = (
id: number,
callback: (error: error | null, task: todo | null) => void
) => {
fetch(`https://jsonplaceholder.typicode.com/todos/${id}`)
.then((response) => {
if (response.ok) {
return response.json();
} else {
throw new error("failed to load data");
}
})
.then((data) => {
callback(null, data);
})
.catch((error) => {
callback(error, null);
});
};
createpromise(1, (error, task) => {
if (error) {
console.error(error);
} else {
console.log(task);
}
});
承诺
promise 提供了比回调更干净的方法,允许我们使用 .then() 和 .catch() 方法以更线性的方式处理异步操作。它们更容易链接,但仍然会因为复杂的操作而变得混乱。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const createpromise = (id: number): promise<object> => {
return new promise<object>((resolve, reject) => {
const data: object = fetch(
`https://jsonplaceholder.typicode.com/todos/${id}`
).then((response) => response.json());
if (data) {
resolve(data);
} else {
reject("failed to load data");
}
});
};
createpromise(1)
.then((data) => console.log(data))
.catch((error) => console.error(error));
异步/等待
与 promise 和回调相比,async/await 提供了一种更具可读性和可管理性的异步代码处理方式。它让我们可以像同步一样编写异步代码,使用 async 关键字将函数标记为异步,并使用 wait 暂停代码执行,直到 promise 解析。这种方法提高了可读性并且更容易调试。
1
2
3
4
5
6
7
8
9
10
11
12
13
type Todo = {
id: number;
userId: number;
title: string;
completed: boolean;
};
const getTodo = async (): Promise<Todo> => {
const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
const data = await response.json();
return data;
};
console.log(getTodo());
为什么使用异步/等待?
提高可读性:async/await 更具可读性且更易于理解,特别是对于具有多个异步调用的复杂代码。 错误处理:它允许使用 try/catch 块进行更简单的错误处理,而不是多个 .catch() 方法。谢谢
以上就是如何处理异步操作的详细内容,更多请关注php中文网其它相关文章!