Open youngwind opened 8 years ago
之前基于co和ES6的generator确实使异步操作写得更好了#49 ,但是,依然不够优雅。这次使用ES7的async来解决这个问题。通过babel,这个语法已经可以应用在生产环境当中了(已经有人这么干了)。
function sleep(timeout) { return new Promise((resolve, reject) => { setTimeout(function() { resolve(); }, timeout); }); } (async function (){ console.log('start'); await sleep(3000); console.log('======='); await sleep(4000); console.log('finish'); })()
在用babel转义async语法的时候,需要提供stage-0的preset,否则会报错
regeneratorRuntime is not defined ...
具体问题参考这儿。
参考资料:
JavaScript中Async/Await优于Promise的6个原因这篇文章比较了async和promise,说明了一些优点,从墙外搬过来的,我觉得讲的不错。
续
之前基于co和ES6的generator确实使异步操作写得更好了#49 ,但是,依然不够优雅。这次使用ES7的async来解决这个问题。通过babel,这个语法已经可以应用在生产环境当中了(已经有人这么干了)。
demo
坑
在用babel转义async语法的时候,需要提供stage-0的preset,否则会报错
具体问题参考这儿。
参考资料: