Skip to content

await 等到之后,做了一件什么事情?

两种情况

  • 不是promise对象
  • 是promise对象

如果不是 promise , await会阻塞后面的代码,先执行async外面的同步代码,同步代码执行完,再回到async内部,把这个非promise的东西,作为 await表达式的结果。 如果它等到的是一个 promise 对象,await 也会暂停async后面的代码,先执行async外面的同步代码,等着 Promise 对象 fulfilled,然后把 resolve 的参数作为 await 表达式的运算结果。

javascript
// async function firstAsync () {
//   return 27
// }

// console.log(firstAsync() instanceof Promise)  // true

// firstAsync().then(val => {
//   console.log(val) // 27
// })
//

async function firstAsync() {
  let promise = new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve('now it is done')
    }, 1000)
  })

  console.log(await promise)
  console.log(await 0)
  console.log(await Promise.resolve(1))
  console.log(2)
  return Promise.resolve(3)
}

firstAsync().then((val) => {
  console.log(val)
})
// now it is done
// 0
// 1
// 2
// 3

async await对比promise的优缺点

优点

  1. 它做到了真正的串行的同步写法,代码阅读相对容易
  2. 对于条件语句和其他流程语句比较友好,可以直接写到判断条件里面
  3. 处理复杂流程时,在代码清晰度方面有优势

缺点

  1. 无法处理 promise 返回的 reject 对象,要借助 try/catch
  2. 用 await 可能会导致性能问题,因为 await 会阻塞代码,也许之后的异步代码并不依赖于前者,但仍然需要等待前者完成,导致代码失去了并发性。
  3. try/catch 内部的变量无法传递给下一个 try/catch,Promise 和 then/catch 内部定义的变量,能通过 then 链条的参数传递到下一个 then/catch,但是 async/await 的 try 内部的变量,如果用 let 和 const 定义则无法传递到下一个 try/catch,只能在外层作用域先定义好。

但async/await确确实实是解决了promise一些问题的。更加灵活的处理异步

Layout Switch

Adjust the layout style of VitePress to adapt to different reading needs and screens.

Expand all
The sidebar and content area occupy the entire width of the screen.
Expand sidebar with adjustable values
Expand sidebar width and add a new slider for user to choose and customize their desired width of the maximum width of sidebar can go, but the content area width will remain the same.
Expand all with adjustable values
Expand sidebar width and add a new slider for user to choose and customize their desired width of the maximum width of sidebar can go, but the content area width will remain the same.
Original width
The original layout width of VitePress

Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.

Spotlight

Highlight the line where the mouse is currently hovering in the content to optimize for users who may have reading and focusing difficulties.

ONOn
Turn on Spotlight.
OFFOff
Turn off Spotlight.