如何在 JavaScript中将axios与async/await一起使用?

Axios 是一个基于promise 的处理异步 HTTP 请求的客户端。本指南将演示如何通过async/await 处理这些请求。

安装和使用

要使用 Axios,您需要使用 npm

npm install axios

安装后,将其导入到您的 JavaScript 文件中

import axios from 'axios';

没有async/await的请求

现在,让我们看看没有 async/await的 Axios 请求是什么样子的。该函数返回一个promise。我们用于将此promise解析为 API 的响应。

import axios from 'axios';
axios.get('https://famous-quotes4.p.rapidapi.com/random')
    .then(response => {
        // Handle response
        console.log(response.data);
    })
    .catch(err => {
        // Handle errors
        console.error(err);
    });
[
  {
    "id": 13190,
    "text": "I don't have the best dating track record.",
    "category": "dating",
    "author": "Lauren Conrad"
  },
  {
    "id": 75560,
    "text": "I save every Christmas card. I keep them all.",
    "category": "christmas",
    "author": "Alison Sweeney"
  }
]

具有async/await的请求

处理promise更好,更干净的方式是通过关键字。由于关键字await,异步函数将暂停,直到promise执行结束。

import axios from 'axios';
const getData = async () => {
	const response = await axios.get(
		`https://famous-quotes4.p.rapidapi.com/random`
	);
};

错误处理

为了处理使用 Axios 的标准 API 调用中的错误,我们使用一个try\catch块。在catch块中,我们可以处理错误。下面是一个示例:

try {
	const res = await axios.get(`https://famous-quotes4.p.rapidapi.com/random`);
} catch (error) {
	// Handle errors
}
posted @ 2022-10-15 02:59  杨树的小三  阅读(281)  评论(0编辑  收藏  举报