バンビのブログ

駆け出しのエンジニアです!日々の疑問など備忘録として書いていきます。

Axios asyncとawait

Axios:

AxiosはAjaxリクエストを簡単にかけるようにしたPromiseベースのjsのライブラリです。

GET通信をするとき

const info
const error

// get()に通信したいURLを記入
axios.get('/user?id=123')
             or
// オプションで第2引数を渡すこともできる
axios.get('/user', params{ id: 123 })

     //通信に成功し、返ってきた値を this.info に代入する
     .then(response => (this.info = response))

     //エラーだった場合はエラーを捕捉する
     .catch(error => (this.error = error))
     
     //続けて書くと成功でも、失敗でもその後実行される処理もかける。PUTでもPOSTでも他でも同様
     .then(function () { 処理 });

POST通信をするとき 第1引数にURLを指定して、第2引数に送信したい値を設定します。

//post送信したいデータを格納する変数を作成
const post-data = { name: 'hoge' };

axios.post('/user', post-data)

    .then(res => {

        //送信成功時の処理
        alert("「" + post-data.name + "」登録完了");
        this.$router.push({path: '/articles/list'});
    })
    .catch(error => {

        //送信失敗時の処理
        alert("「" + post-data.name + "」登録失敗");
        console.log(error, post-data);
    });

PUT通信 データ更新するとき

//更新したいID設定用の変数
const id = '1000';

//更新データ用変数
const modify = { name: 'hoge' };


Axios
    //第1引数にURL設定をし、第2引数に更新するデータを設定
    .put('/api/sample/' + id, modify)
    .then(res => {
        //通信成功時の処理
        alert("「" + modify.name + "」更新完了");

     // リダイレクトさせる
        this.$router.push({path: '/articles/list'});
    })
    .catch(error => {

     //通信失敗時の処理
        alert("「" + modify.name + "」更新失敗");
        console.log(error, id, modify);
    });

DELETE通信をするときは、他と違い第2引数に設定する値のキーを「data」に設定して書かなければだめ。例 {data: params}

//削除対象のIDを設定
const id = '1000';

//削除内容を設定
const params = { name: 'hoge' };

Axios
    //delete通信をし、第1引数にURLとIDを設定し、第2引数に {data: 削除したいデータ} を設定
    .delete('/api/sample/' + id, {data: params})

    .then(res => {
        // 成功時の処理
        alert("「" + params.name + "」削除成功");
        this.$router.push({path: '/sample/list'});
    })
    // 失敗時の処理
    .catch(error => {
        alert("「" + params.name + "」削除失敗");
        console.log(error, id, params);
    });

async awaitを使用したいとき asyncはPromiseオブジェクトを返しますという宣言でつけるらしい。

// asyncをつけてメソッドを定義
async function getUser() {

  //try,catchでエラーを捕捉できるようにしておく
  try {

  //Promiseオブジェクトで「resolve」が返ってくれば実行される
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {

  //Promiseオブジェクトで「reject」が返ってくれば実行される
    console.error(error);
  }
}

複数のaxiosが実行されたあとに実行したい処理がある時(Promise.allみたいな感じ)

// 1個目のメソッド
function getUserAccount() {
  return axios.get('/user/12345');
}

// 2個目のメソッド
function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

// Promise.allとほぼ同じで、配列でメソッドを囲う
axios.all([getUserAccount(), getUserPermissions()])

  //囲った2つのメソッドが実行されたら以下の処理が実行される
  .then(axios.spread(function (acct(1個目のメソッドの返り値のこと), perms(2個目のメソッドの返り値のこと)) {
    // Both requests are now complete
  }));

asyncawait.thenの書き方を簡潔にかけるようにしたものです。 asyncをつけるとPromiseオブジェクトが返却されるようになります。

//asyncでかくとこうなる

async function asyncFunc (arg) {

  // 引数の「arg」もここで使える
  const message = 'Hello async';
  return message;
}

//上記をPromiseで書くとこうなります。
function asyncFunc (arg) {
  return new Promise((resolve) => {
    // もちろん引数のargはここで使えます
    const message = 'Hello async';
    resolve(message);
    return;
  });
}

このくらい差があります。

async = 「return new Promise」 と 「resolve」 が入ってるってイメージなのかな?

awaitasync関数内で使用できる予約語です。 Promiseがわかれば何も難しいことはありません。安心してくださいまし。

// Promiseで書いた場合
function main() {
    getX().then(x => {
        getY().then(y => {
            console.log(x + y)
        })
    })
}

function getX() {
    return Promise.resolve(1)
}

function getY() {
    return Promise.resolve(2)
}

main()

//async awaitで書いた場合
async function main() {
    const x = await getX()
    const y = await getY()
    console.log(x + y)
}

async function getX() {
    return 1
}

async function getY() {
    return 2
}

main()
//async awaitで書いたほうが読みやすよね。

//async awaitでaxiosを使ってみる
async function asyncFunc () {

  //axiosでGET通信
  const res1 = await axios.get('/some/path1');

  //res1を使ってaxiosでGET通信(ということは、res1が完了しないと実行してもうまくいかない。)
  const res2 = await axios.get(`/some/${res1.data.nextpath}`);

  console.log(res1.data + res2.data); // => "some data"
}

画像を送信する時 headers'Content-Type': 'multipart/form-data'を設定すること

//HTML
<input id="file-input" type="file" />

//javascript
//paramsにFormに入力した値格納
var params = new FormData()

var file = document.getElementById("file-input")

// ファイルをparamsに格納
params.append('file', file.files[0])

//第3引数にheadersを追加して、'Content-Type': 'multipart/form-data'を設定してあげる必要があります。
const res = await axios.post(url, params, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
})

画像を取得するときに方法。うまく行かないときや、メソッドを書くときはheaderscontentTyperesposeTypeなどが正しいか確認しよう。

//axiosのインスタンス作成し、responseTypeかContent-Typeを指定する。
var instance = axios.create({
  'responseType': 'arraybuffer',
  'headers': {
    'Content-Type': 'image/png'
  }
});
  //こんな感じに書ける
  axios.get(url, { responseType: "arraybuffer", 'headers': {'Content-Type': 'image/png'}});