Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
youngwind opened this issue Apr 15, 2016 · 1 comment
Open

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

youngwind opened this issue Apr 15, 2016 · 1 comment
Labels

Comments

@youngwind
Copy link
Owner

youngwind commented Apr 15, 2016

之前基于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/
@madneal
Copy link

madneal commented Apr 7, 2017

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants