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);
});

最新文章

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

热门文章

  1. Android开发进度03
  2. vue svg的使用
  3. 如何成为资深的python专家
  4. AT1145 ホリドッグ
  5. 调整mysql数据库最大连接数
  6. [TypeScript] Generic Functions, class, Type Inference and Generics
  7. hive 运行sqlclient异常
  8. 为powerpc交叉编译nginx
  9. Math类概述及其成员方法
  10. [Swift]数组(Array)最强解析