[Typescript] Promise based delay function using async / await
2024-10-01 15:16:58
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();
cb('1s')
await delay();
cb('2s')
await delay();
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);
});
最新文章
- Hibernate 系列 04 - Hibernate 配置相关的类
- Mysql如何创建短索引(前缀索引)
- AXIS 调用 webservice服务时传递 服务器验证需要的用户名密码
- 用Qt Creator 对 leveldb 进行简单的读写
- 初识Android NDK
- [issue] dyld`dyld_fatal_error: ->; 0x120015088 <;+0>;: brk #0x3
- C编译器剖析PDF文档及UCC编译器162.3
- jQuery 学习笔记(未完待续)
- Mysql监控工具小集合
- 【CF】3B Lorry
- javascript——面向对象程序设计(2)
- CF 319C(Kalila and Dimna in the Logging Industry-斜率DP,注意叉积LL溢出)
- C---数组名作函数参数
- quartus2中FPGA管脚分配保存方法(转)
- Linux audio驱动模型
- python数据存储技巧
- MacOS安装Go2Shell
- android开发(0):android studio的下载安装与简单使用 | sdk的安装与编译运行
- libgdx学习记录8——对话框Dialog
- stty(set tty)