在 typescript 中,我们有多种方法来处理异步操作:回调、promise 和 async/await。异步编程使我们能够管理可能需要时间的操作,例如从 api 获取数据,而不会阻塞其他代码的执行。
回调是作为参数传递给另一个函数的函数,并在任务完成后执行。虽然回调适用于简单的任务,但当需要链接操作时,它们很快就会变得不可读。
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() 方法以更线性的方式处理异步操作。它们更容易链接,但仍然会因为复杂的操作而变得混乱。
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 解析。这种方法提高了可读性并且更容易调试。
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());
谢谢
以上就是如何处理异步操作的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号