LoginSignup
50
56

More than 5 years have passed since last update.

fetch,async/awaitでAjax通信

Posted at

前提

fetch

Fetch 概説 - Web API インターフェイス | MDN

XMLHttpRequestの代替。
PromiseベースのAjax仕様のAPI。

polyfillを忘れがちなので注意。
https://github.com/github/fetch

async function

async function - JavaScript | MDN - Mozilla

関数定義の前にasyncをつけることで、その関数をAsyncFunctionにする。
暗黙的にPromiseを返す関数。

await

await - JavaScript - MDN - Mozilla

async functionの実行を一時停止し、関数のPromiseの結果を待つ。
fetchはPromiseを返すので相性が良い。

サンプル

お天気のAPI(OpenWeatherMap)を叩くサンプル。

まずは定数を準備。

const API_KEY = '${API_KEY}';
const CITY = 'Tokyo';
const URL = `http://api.openweathermap.org/data/2.5/forecast?q=${CITY},jp&units=metric&APPID=${API_KEY}`;

fetchを使用したサンプル。

fetch(URL)
    .then(res => {
        if(res.ok){
            return res.json();
        } else {
            throw new Error();
        }
    })
    .then(myJson => {
        console.log(JSON.stringify(myJson));
    })
    .catch(err => {
        console.log(err);
    })

fetch,async/awaitを使用したサンプル。

async function getWeather() {
    const res = await fetch(URL);
    const data = await res.json();
    return data;
    // ↓無理やり一行で書くとこうなる
    // return await (await fetch(URL)).json();
}
getWeather()
    .then(data => {
        console.log(JSON.stringify(data));
    })
    .catch(err => {
        console.log(err);
    })
50
56
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
50
56