LoginSignup
5
2

More than 5 years have passed since last update.

JS基礎ーasync/await

Last updated at Posted at 2018-06-24

初めに

非同期処理は、JavaScript (Node.js) で開発する上で避けては通れない。
自分は業務中でよくPromiseで非同期処理を行いますが、今回はasync/awaitとの仕組みを使ってみる。

async/awaitは何

簡単に言うとasync/awaitとは簡潔に非同期処理が書けるやつ。
基本的な形式:

async function Fn(){
    var variable = await getVariable(name);
}

async :関数やラムダ式の前につけ、戻り値をPromiseに加工する
await :Promise.resolveの値を取得するまでブロッキングし、同期処理のふうに非同期処理を書ける

検証しましょう:


async function testAsyncAwait() {
    return 'show asyncawait';
}

const result = testAsyncAwait();
console.log(result);

実行すると

PS C:\Users\ma\work\nodejs> node .\async_await.js
Promise { 'show asyncawait' }

戻り値がPromise形とのことが分かった。

エラー処理

awaitの後ろについたのでpromiseオブジェクトなので、rejectedの可能性がある。
下記のようにtry...catchでエラーをcatchする。

async function myFunction() {
  try {
    await Promise();
  } catch (err) {
    console.log(err);
  }
}

終わり

そもそもasync/awaitもPromiseを利用しているため、Promise自体を理解しないとまずいかも。。
次回はPromiseを整理してみましょう。

5
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
5
2