0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Promiseとasync/awaitの使い方

Last updated at Posted at 2020-02-26

非同期で処理するためのPromise、async/awaitの基本的な使い方をまとめました。
詳しく知りたい方は参考文献をご確認ください。

Promise

Promiseオブジェクトを返す

return new Promise((resolve, reject) => {})

Promiseの結果を返す

resolveする

Promiseのresolveを実行する

return new Promise((resolve, reject) => {
  resolve('成功です')
})

rejectする

Promiseのrejectを実行する

return new Promise((resolve, reject) => {
  reject('失敗です')
})

async/await

処理の結果を待つ

async function sample() {
  const result = await samplePromise()
  console.log(result.data)
}

並列で処理する

async function sample() {
  const array =[5, 10, 15]
  const promiseAll = await Promise.all(
    array.map(async (value) => {
      return await samplePromise(value)
    })
  )

  return promiseAll
}

例外処理(エラーハンドリング)

async function errorHandling() {
  try {
    const result = await throwError()
    return result
  } catch (err) {
    throw err
  }
}

参考文献

この記事は以下の情報を参考にして執筆しました。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?