LoginSignup
1
0

【JavaScript】async/awaitとaxios、非同期通信について

Posted at

axiosとは

HTTP通信(データの更新・取得)など、HTTPリクエストのやり取りを簡単に行うことができる、JavaScriptのライブラリです。Node.jsで記述されています。APIを提供するクラウドサービスに対して、データを送受信することができます。

非同期にHTTPメソッド(GET・POST・PUT・DELETE通信など)を取り扱えます。

非同期処理とは

時間の掛かる処理の結果を待たずにすぐ次の処理を実行できる仕組みです。Promiseを使うと簡単に実現できます。

Promiseとは、非同期処理の状態を監視するためのオブジェクトで、非同期処理を同期処理のように扱える書き方です。

使う場面

JSONデータを提供しているAPIと接続して、データを取得することが多いです。

Webの場合、サーバーの中で外部にデータを提供している機能(またはそnページ)のことをAPIとよびます。

async/awaitとは

async/awaitを使うことによって、Promiseによる非同期処理をより簡潔に記述することができます。

Promiseのコードはthenを使ってチェーンを繋いでいくので、単調で長いコードになりやすです。

複数のPromise処理を実行する例

getDate()
.then(function(data) {

    return getYear(data)

}) .then(function(year) {

    return getSomething(year)

}) .then(function(item) {

    getAnotherThing(item)

})

上記のように長くなってしまいます。
そこで登場するのがasync/awaitです。

async/awaitの使い方

async

async function() { }

asyncを記述すると、この関数はPromiseを返すようになります。

await

await Promise処理

awaitはPromise処理の結果が返ってくるまで一時停止する演算子です。

awaitはasyncで定義された関数の中だけでしか使えません。

今回書いたコード

http/api.js
import axios from "axios";

const api = axios.create({
    baseURL: "http://localhost:8000/api/v1"
})


export default api
pages/RecipePages.vue
<script setup>
import { onMounted } from "vue";
import api from "../http/api"

onMounted(async() => {
    const { data } = await api.get('/recipes')
    console.log(data)
})
</script>

実行

image.png

データベースに」格納されているデータを取得できました。

以下のようにしてCRUDを定義しました。

httprecipe-api.js
import api from "./api";

const resource = "/recipes"

export const allRecipes = () => api.get(resource)

export const createRecipe = task => api.post(resource, recipe)

export const updateRecipe = (id, recipe) => api.put('${resource}/${id}', recipe)

export const removeRecipe = id => api.delete('${resource}/${id}')

export const completeRecipe = (id, recipe) => api.put('${resource}/${id}/complete', recipe)

修正を加えてコードを簡潔にします。

pages/RecipePages.vue
<script setup>
import { onMounted } from "vue";
import { allRecipes } from "../http/recipe-api"

onMounted(async() => {
    const { data } = await allRecipes()
    console.log(data)
})
</script>

実行

image.png

実行結果を変えずに修正できました。

1
0
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
1
0