LoginSignup
0
1

More than 3 years have passed since last update.

async/awaitの使い方について(超初級)

Posted at

今回はプログラミング学習において避けては通れない非同期処理について学習したことを記事にさせていただきたいと思います。

まず非同期処理とは
処理Aを実行中に処理Bを実行するときに処理Aは処理を進めたまま処理Bも処理を進めます。

逆に同期処理とは
処理Aを実行中に処理Bを実行するときは処理Aの処理を一度止めたから処理Bを進め、その処理が終わってから処理Aを再開する流れになってます。
qiita.jpg

非同期処理の方が処理を止めずに進めるので早いのですがデメリットとしては
処理Aのレスポンスを利用して処理Bを実行したいときにはレスポンスが帰ってくる前に処理Bが実行され思っていた結果が得られないことがあります。
よくconsoleで表示した内容がundefinedになって困ったことはありませんか?

これを解決するのが今回紹介するasync/awaitです。
まずはasync/awaitを使わないで行った処理です。

main.js
function callApi() {
  const res = fetch("https://jsonplaceholder.typicode.com/posts");
  const users = res.json();
  console.log(users);
}

callApi();

コンソールの結果

index.html
index.js:3 Uncaught TypeError: res.json is not a function
    at callApi (index.js:3)
    at index.js:7

エラーが出ちゃいましたね。
これはfetch()で取得した結果が変数resに入る前にres.json()を呼び出したために起きたエラーです。

次はasync/awaitを使って書いてみましょう

main.js
async function callApi() {
  const res = await fetch("https://jsonplaceholder.typicode.com/posts");
  const users = await res.json();
  console.log(users);
}

callApi();

コンソールの結果

index.html
(100) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {userId: 1, id: 1, title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", body: "quia et suscipit↵suscipit recusandae consequuntur …strum rerum est autem sunt rem eveniet architecto"}
1: {userId: 1, id: 2, title: "qui est esse", body: "est rerum tempore vitae↵sequi sint nihil reprehend…aperiam non debitis possimus qui neque nisi nulla"}
2: {userId: 1, id: 3, title: "ea molestias quasi exercitationem repellat qui ipsa sit aut", body: "et iusto sed quo iure↵voluptatem occaecati omnis e…↵molestiae porro eius odio et labore et velit aut"}
3: {userId: 1, id: 4, title: "eum et est occaecati", body: "ullam et saepe reiciendis voluptatem adipisci↵sit … ipsam iure↵quis sunt voluptatem rerum illo velit"}
.
.
.

しっかりとres.jsonの結果が表示されました。
これはcallApi()に対してasyncをつけることによって非同期関数にします。
この関数の中ではawaitが使うことができ、
await fetch("https://jsonplaceholder.typicode.com/posts");
が完了するまでは次の処理には進めないようにしてます。
よってres.json()の中身がundefinedにはならず上手く実行結果を得ることができました。
非同期処理に関してはasync/await以外にもやり方があるのですがこのやり方が一番使われていると思います。

以上がasync/awaitの使い方(超初級)でした。

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