js中解决异步编程的方案(Solution to asynchronous programming in JS)

一、事件监听

  • 优点:与回调函数相比,事件监听实现了代码的解耦,方便代码管理
  • 缺点:使用不方便,每次都要手动地绑定和触发事件

二、回调函数

回调是一个函数被作为一个参数传递到另一个函数里,在那个函数执行完后再执行。( 即:B函数被作为参数传递到A函数里,在A函数执行完后再执行B )

  • 优点:简单,方便,易用
  • 缺点:易造成回调函数地狱,回调函数中嵌套多个回调函数,因为多个异步操作造成强耦合,代码乱做一团,无法管理

三、promise

  • 优点:将回调函数嵌套调用变成了链式调用,解决了回调地狱,逻辑更强,执行顺序更清楚
  • 缺点:代码冗余,异步操作都被包裹在Promise构造函数和then方法中,主题代码不明显,语义不清楚

四、async/await

  async函数是generrator函数的语法糖,它相当于一个自带执行器的generator函数  async函数中的await接收一个Promise对象

  • 优点:最简洁,最符合语义,使得异步代码看起来像同步代码,避免了嵌套代码,- 最适合处理多个Promise异步操作
  • 缺点:js语言自带的async执行器功能性可能没有co模块等执行器强,如果多个异步代码没有依赖性却使用了 await 会导致性能上的降低
————————

1、 Event listening

  • Advantages: compared with callback function, event monitoring realizes code decoupling and facilitates code management
  • Disadvantages: it is inconvenient to use. You have to manually bind and trigger events every time

2、 Callback function

A callback is a function that is passed as a parameter to another function and executed after that function is executed. (that is, function B is passed to function a as a parameter, and then function B is executed after function a is executed)

  • Advantages: simple, convenient and easy to use
  • Disadvantages: it is easy to cause callback function hell. Multiple callback functions are nested in the callback function, because multiple asynchronous operations cause strong coupling, and the code is messy and unmanageable

三、promise

  • Advantages: the nested call of callback function is changed into chain call, which solves the callback hell, has stronger logic and clearer execution order
  • Disadvantages: code redundancy, asynchronous operations are wrapped in promise constructors and then methods, the subject code is not obvious, and the semantics is not clear

四、async/await

Async function is the syntax sugar of the generator function. It is equivalent to a generator function with its own actuator. Await in async function receives a promise object

  • Advantages: it is the most concise and semantic, which makes asynchronous code look like synchronous code, avoids nested code, and is most suitable for handling multiple promise asynchronous operations
  • Disadvantages: the functionality of the async executor built in JS language may not be as strong as that of the co module. If multiple asynchronous codes do not have dependencies but use await, the performance will be reduced