まだらもよう

Qiitaに投稿できないメモ書きなど

async, await

async

asyncは関数の前で宣言する。async functionは以下の仕様を持つ

  • Promiseを返す
  • returnした値をresolveする
  • throwした値・例外をrejectする
async function hoge(isSuccess) {
  if (isSuccess) {
    return 'hoge'
  }
  throw new Error('Failed.')
}

hoge(true)
  .then(result => {
    console.log(result) // ここが処理される
  })
  .catch(err => {
    console.log(err)
  })

hoge(false)
  .then(result => {
    console.log(result)
  })
  .catch(err => {
    console.log(err) // ここが処理される
  })

await

async function内で、resolveかrejectされるまで待ってくれる

async function hoge(isSuccess) {
  if (isSuccess) {
    return 'hoge'
  }
  throw new Error('Failed.')
}

async function awaitHandler() {
  const result = await hoge(true)
  console.log(result)
}

async function awaitHandler2() {
  hoge(true).then(result => {
    console.log(result)
  })
}

async function handler() {
  const result = hoge(true)
  console.log(result)
}

awaitHandler() // hoge
awaitHandler2() // hoge
handler() // Promise obj