youngwind / blog

梁少峰的个人博客

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

异步回调更优雅的解决方式:async

youngwind opened this issue · comments

之前基于co和ES6的generator确实使异步操作写得更好了#49 ,但是,依然不够优雅。这次使用ES7的async来解决这个问题。通过babel,这个语法已经可以应用在生产环境当中了(已经有人这么干了)。

demo

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 ...

具体问题参考这儿

参考资料:

  1. http://es6.ruanyifeng.com/#docs/async#async函数
  2. http://www.alloyteam.com/2015/12/hey-async-await-me/
  3. http://aisk.me/using-async-await-to-avoid-callback-hell/

JavaScript中Async/Await优于Promise的6个原因这篇文章比较了async和promise,说明了一些优点,从墙外搬过来的,我觉得讲的不错。