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

javascript中的异步编程 #3

Open
CJianYu opened this issue Nov 20, 2018 · 0 comments
Open

javascript中的异步编程 #3

CJianYu opened this issue Nov 20, 2018 · 0 comments

Comments

@CJianYu
Copy link
Owner

CJianYu commented Nov 20, 2018

我们都知道,javascript是单线程的,但为什么如此设计呢?因为不想让浏览器变得太复杂。多线程需要共享资源,如果一个线程修改了一个dom,另一个线程同时修改同一个dom,那听哪个线程的?所以,从诞生的时候,javascript就是单线程的。既然是单线程,就有同步和异步之分。

同步就不必说了,异步编程有如下几种方法:

  1. 回调函数
  2. 事件监听
  3. 发布/订阅者模式
  4. 用Promise对象
  5. Generator函数

1.回调函数

很容易理解,将一个作为另一个函数的回调函数,达到执行完一个函数后执行另一个函数的效果。缺点也很明显,函数高度耦合,不利于维护,且一个函数只能有一个回调函数。
carbon

2.事件监听

以事件为驱动,为一个函数添加一个触发事件,事件触发时执行另一个函数:

image

这个方法的缺点是,以事件驱动很难判断主流程,不利于代码阅读。

3.发布/订阅者模式(观察者模式)

实现发布订阅模式如下:
image

4.用Promise对象

Promise的出现很好地解决了回调地狱的问题。基本用法如下:
carbon 1
要想一个函数执行完后再执行另一个函数,可以采用如下做法,这样做当一个函数没有执行成功,另一个函数也将不执行:
carbon 2

5.Generator函数

Generator是es6新特性,解决promise可能出现的一堆then导致的语义不清晰的问题
carbon 3

参考链接:
http://www.ruanyifeng.com/blog/2012/12/asynchronous%EF%BC%BFjavascript.html
https://www.cnblogs.com/lovesong/p/5272752.html

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

No branches or pull requests

1 participant