32
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

axiosとasync/awaitの関係性

32
Posted at

axiosはhttpライブラリですが、正直よくわからずなんとなくasync/awaitと合わせて使うといい感じでデータが取得できると思い、使っていました。
事実それで取得できていました。
しかし、エラーハンドリングやその他処理を考える時に理解が足りないと感じたので、
改めてどういった挙動をするのか理解したかった為、示します。

試してみる

axios.js

//1.async・awaitなしのaxios
const response = axios.get('https://●●●※webapiを想定');
console.log(response);

⬇︎コンソールで確認(戻り値はPromiseオブジェクト)

/*
Promise {<pending>}
__proto__: Promis
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Object
*/


//2.asyncのみ定義したaxios
async function test(){
  const response = axios.get('https://●●●※webapiを想定');
  console.log(response);
}
test();

⬇︎コンソールで確認(戻り値はPromiseオブジェクト)

/*
Promise {<pending>}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Object
*/


//3.async・awaitを定義したaxios
async function test(){
  const response = await axios.get('https://●●●※webapiを想定');
  console.log(response);
}
test();

⬇︎コンソールで確認(戻り値は実データ)

/*
{data: {…}, status: 200, statusText: "", headers: {…}, config: {…}, …}
*/


//async・awaitを定義したaxiosを違う関数から呼び出すパターン
async function asyncFunction(){
  const response = await axios.get('https://●●●※webapiを想定');
  return respnonse;
}
function test(){
  const response = asyncFunction();
  console.log(response);
}
test();

⬇︎コンソールで確認(戻り値はPromiseオブジェクト)

/*3番で実データになっていたはずがPrimiseオブジェクトにもどっている!!
Promise {<pending>}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Object
*/


まとめ 
・axiosはPromiseを返します。
・asyncはPromiseを返します。
・asyncとaxiosではPromiseを返します。
・axiosをasync/awaitすると実データを返します。(ただし関数内部のみです)
・別関数からaxiosのasync/awaitを呼び出すとPromiseを返します。
 これはasync/awaitが常にPromiseを返すことを意味します。

以上です。

32
25
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
32
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?