[Typescript] Promise based delay function using async / await
typescriptasync Using Function Promise based await delay
2023-09-14 09:00:50 时间
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
const delay = (ms) => new Promise(res => setTimeout(res, ms)); const runAsync = async (cb) => { await delay(100); cb('1s') await delay(1000); cb('2s') await delay(1000); cb('3s') } runAsync((m) => { console.log(m)})
or normal promise:
const delay = ms => new Promise(res => setTimeout(res, ms)); const runAsync = cb => { Promise.resolve() .then(() => { cb("1s"); return delay(1000); }) .then(() => { cb("2s"); return delay(1000); }) .then(() => { cb("3s"); return delay(1000); }); }; runAsync(m => { console.log(m); });
相关文章
- [Typescript] Function Overloads vs. Union Types
- [Typescript 4.9] Satisfies operator
- [Typescript] Zod in action
- [Typescript] Tips: Ensure that all call sites must be given value
- [Typescript Challenges] 6 Easy - Exclude
- [React Typescript 2022] Use TypeScript to Type a React Class Component
- [Typescript] Declaring Globals for a Library
- [Typescript] 121. Hard - IsPalindrome
- [Typescript] Only Type import or export
- [Typescript] Scopes and TypeParams
- SAP Spartacus TypeScript和编译后的JavaScript命名规范
- TypeScript Mixins 概念介绍
- TypeScript里get属性的实现
- TypeScript里的完整函数定义语法
- 带你了解Typescript的14个基础语法