attention front-end small Ou , read more original technical articles

Asynchronous programming

  • ES6 adds the official Promise reference type, which supports more elegant definition and organization of asynchronous logic
  • In the next few versions, use the async and await keywords to define the mechanism of asynchronous functions

related code →

Synchronous and asynchronous

  • Synchronous behavior execute processor instructions in memory 1612f41227a25c

    • Each instruction is in 1612f41227a2b1 single thread in in the order of
    • After each instruction is executed, the state of the program can be inferred, and immediately obtains the stored in the system local (or register or system memory) of 1612f41227a2f6
let x = 3 // 操作系统在栈内存上分配一个存储浮点数值的空间
x = x + 4 // 针对这个值做一次数学计算,并把计算结果写回之前分配的内存中
  • asynchronous behavior similar to system interrupt

    • The entity outside the current process can trigger code execution, usually executed in timing callback
    • The execution thread does not know when stores the information to the system local (or register or system memory), depending on the callback, it is appropriate to dequeue from the message queue and execute
let x2 = 3 // 操作系统在栈内存上分配一个存储浮点数值的空间
setTimeout(() => {
  x = x + 4 // 执行线程不知道x值何时会改变,取决于回调何时从消息队列出列并执行
}, 1000)

Asynchronous programming in the past

  • Early JS only supports callback function indicating asynchronous operation, multiple asynchronous operations requires deep nesting callback function ( callback hell )
function double(value) {
  setTimeout(() => {
    setTimeout(() => {
      console.log(value * 2)
    }, 2000) // 2000毫秒后,JS运行时会把回调函数推到消息队列上等待执行
  }, 1000) // 1000毫秒后,JS运行时会把回调函数推到消息队列上等待执行
}
double(3) // 6(约3000毫秒后),double()函数在setTimeout成功调度异步操作后,立即退出

Asynchronous return value

  • If the setTimeout operation returns a useful value, you can provide a callback for the asynchronous operation and pass this value to the place where it is needed
function double2(value, callback) {
  setTimeout(() => {
    callback(value * 2) // 1000毫秒后,把回调函数推到消息队列上
  }, 1000)
}
double2(3, (x) => console.log(`I was given: ${x}`)) // 'I was given: 6'(约1000毫秒后)

Failure handling

  • Handle the failure of asynchronous operation in the callback model (success callback & failure callback)
  • The method is no longer desirable , because the callback must be defined when initializes the asynchronous operation only exists for a short time, and the callback that takes the return value as a parameter must be prepared to receive it.
function double3(value, success, failure) {
  setTimeout(() => {
    // 必须在初始化异步操作时定义回调
    try {
      if (typeof value !== 'number') {
        throw 'Must provide number as first argument'
      }
      success(value * 2)
    } catch (error) {
      failure(error)
    }
  }, 1000)
}
const successCallback = (x) => console.log(`Success: ${x}`)
const failureCallback = (e) => console.log(`Failure: ${e}`)
double3(3, successCallback, failureCallback) // 'Success: 6'(约1000毫秒后)
double3('3', successCallback, failureCallback) // 'Failure: Must provide number as first argument'(约1000毫秒后)

Nested asynchronous callback

  • If asynchronous return value depends on another asynchronous return value , it is necessary nested callback ( callback Hell , does not scale, the code is difficult to maintain)
function double4(value, success, failure) {
  setTimeout(() => {
    try {
      if (typeof value !== 'number') {
        throw 'Must provide number as first argument'
      }
      success(value * 2)
    } catch (error) {
      failure(error)
    }
  }, 1000)
}
const successCallback2 = (x) => {
  double4(x, (y) => console.log(`Success: ${y}`)) // 异步返回值依赖另一个异步返回值,嵌套回调产生“回调地狱”
}
const failureCallback2 = (e) => console.log(`Failure: ${e}`)
double4(3, successCallback2, failureCallback2) // 'Success: 12'(约2000毫秒后)

Summary & Questions

  • In terms of execution threads and memory storage, what is the difference between synchronous behavior and asynchronous behavior?
  • Write a piece of code, pass the return value of setTimeout as a callback to the function, and execute this function to get the result
  • Write a piece of code to handle the success/failure of asynchronous operations in the callback model, and talk about why this method is no longer desirable
  • How is callback hell formed? What are the disadvantages?

小讴
217 声望16 粉丝