码迷,mamicode.com
首页 > 其他好文 > 详细

[Typescript] Promise based delay function using async / await

时间:2018-01-24 22:02:10      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:rap   learn   div   time   gpo   using   blog   settime   out   

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

 

[Typescript] Promise based delay function using async / await

标签:rap   learn   div   time   gpo   using   blog   settime   out   

原文地址:https://www.cnblogs.com/Answer1215/p/8343347.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!