0
2

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.

非同期処理async,awaitについて

Last updated at Posted at 2020-09-27

非同期処理について

JavaScriptでは非同期処理を行う選択肢は主に3種類あります。
「Promise」「async,await」「Observable」です。
ここではasync,awaitについて記載します。

async,awaitの特徴

async,awaitはPromiseの派生です。
Promiseを簡略化して記載することができます。
また、非同期処理を直列で実行したい場合に入れ子にならない利点があります。
Promiseとasync,awaitは混同して利用することができます。

構文

Promiseで記載した非同期処理をasync,awaitに書き換えます。

Promise

method() {
  asyncFunction(parameter).then(closureOfSucceedCase).catch(closureOfFailureCase);
}

async, await

async method() {
  try {
    const response = await asyncFunction(parameter);
  } catch (error) {
    // 異常系処理
  }
}

PromiseをreturnするasyncFunctionの前にawaitをつけて呼び出すことで、
同期呼び出しのように呼び出すことができます。
responseにはPromiseでthen()で渡されるパラメータがセットされます。
catchケースは、Promiseでcatch()が呼ばれる時に動きます。
また、awaitを利用する処理を書いている関数には必ずasyncを書かなければなりません。
asyncが付いた関数を呼ぶ関数にもasyncをつけなければなりません。

動作する順序

下記の順で処理が動きます。
awaitは非同期処理が完了するまで次の行に移りません。

async method() {
  // ①
  try {
    // ②
    const response = await asyncFunction(parameter);
    // ③ (非同期成功時)
  } catch (error) {
    // 異常系処理
    // ③ (非同期失敗時)
  }
  // ④
}

メリット

下記のように非同期処理を連続して実行したい場合に、Promiseのような入れ子にはならず
見易くなる点がメリットです。

const response1 = await asyncFunction1(parameter);
const response2 = await asyncFunction2(parameter);
const response3 = await asyncFunction3(parameter);
0
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?