Louis's blog
GitHub
GitHub
  • 瀏覽器運作原理
  • 閉包
  • this
  • arguments 和 array-like
  • apply、call、bind
  • 函式程式設計
  • 物件和原型
  • 原型鏈和繼承
  • ES6 和 Class
  • ES6 中新增的數據類型
  • ES6 語法糖
  • var、let、const
  • ES7~ES12
  • Strict Mode
  • 補充
  • Proxy 和 Reflect
  • Promise
  • Iterator
  • 生成器
  • async、await
  • Event loop
  • 錯誤處理
  • 模塊化
  • 套件管理工具
  • JSON
  • WebStorage
  • IndexDB
  • Cookie
  • BOM
  • DOM
  • 防抖(debounce)和節流(throttle)
  • Deep copy
  • 事件總線

async、await

ES8 提供的一種基於生成器的語法糖,在函數開頭加上 async 就代表是一個非同步函數:

async function foo() {}

非同步函數永遠返回一個 Promise:

async function foo() {
  return '123'
}

const promise = foo()

promise.then((res) => {
  console.log(res)
})

如果在非同步函數中拋出異常,可以使用 catch 進行捕獲 :

async function foo() {
  throw new Error('-----')
}

const promise = foo()

promise
  .then((res) => {})
  .catch((err) => {
    console.log(err)
  })

在非同步函數中可以透過 await 關鍵字獲取 promise 的返回結果,在這等待結果返回的過程中都是同步執行的:

async function foo() {
  const res = await new Promise((resolve) => {
    resolve('123')
  })
  console.log(res)
}
foo()
Edit this page
Last Updated:
Contributors: louis, louis61619
Prev
生成器
Next
Event loop