[TypeScript] Simplify asynchronous callback functions using async/await
typescriptasync Using await Functions callback Asynchronous
2023-09-14 09:00:52 时间
Learn how to write a promise based delay function and then use it in async await to see how much it simplifies code over setTimeout.
Lets say you want to call a function after 1s, 2s, 3s. You can use setTimeout, or you can wrap it up into a simple delay function that works with async/await
We want to conver this code
const run = (cb) => { setTimeout(() => { cb('1s'); setTimeout(() => { cb('2s'); setTimeout(() => { cb('3s'); }, 1000); }, 1000); }, 1000); }
to:
const delay = (ms) => new Promise(res => setTimeout(res, ms)); const runAsync = async (cb) => { await delay(1000); cb('1s'); await delay(1000); cb('2s'); await delay(1000); cb('3s'); } runAsync((time) => console.log(time));
相关文章
- 浅谈TypeScript泛型T和any的区别
- 计算时间差工具类(TypeScript/JavaScript)
- typescript 接口_typeScript
- ESLint: Typescript + React + TSX 集成
- Getting Started: Ionic + Capacitor + React + Typescript + Android
- TypeScript中泛型及泛型函数、泛型类、泛型接口,泛型约束,一文读懂
- 【TypeScript】的安装方式
- 简单的贪吃蛇小游戏—TypeScript练习
- TypeScript学习笔记(二)—— TypeScript基础
- 「使用 webpack 5 从0到1搭建React + TypeScript 项目环境」3. 资源模块
- TypeScript-tsx文件webstorm无法识别alias配置解决方法
- Flow 与 Typescript:哪个更适合你的项目?
- 解决 Typescript 文件被识别为视频的问题
- Typescript 全栈最值得学习的技术栈 TRPC
- 在TypeScript中使用装饰器