欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > 异步编程与axios技术

异步编程与axios技术

2025/5/26 6:13:05 来源:https://blog.csdn.net/weixin_72255945/article/details/148201809  浏览:    关键词:异步编程与axios技术

异步编程技术是一种允许程序在执行耗时操作(如网络请求、文件读写)时,不阻塞主线程继续执行其他任务的编程范式。它通过事件循环、回调函数、Promise、协程等机制实现非阻塞操作,从而提升应用程序的性能和响应性。

以下从 JavaScript/TypeScriptReactNext.jsPython 的 FastAPIJava 的 Spring Boot 以及 axios 技术的实现方式进行说明,并附上 axios 的使用方法。


1. JavaScript/TypeScript 中的异步编程

JavaScript 是单线程语言,通过事件循环机制实现异步操作。主要方式包括:

回调函数(Callback)
  • 最早的异步处理方式,但容易导致“回调地狱”。
    setTimeout(() => {console.log("第一步完成");setTimeout(() => {console.log("第二步完成");}, 1000);
    }, 1000);
    

不利于阅读与维护。

Promise
  • 避免回调地狱,通过链式调用管理异步操作。
    new Promise((resolve, reject) => {setTimeout(() => resolve("第一步完成"), 1000);
    })
    .then(result => {console.log(result);return new Promise((resolve, reject) => {setTimeout(() => resolve("第二步完成"), 1000);});
    })
    .then(result => console.log(result));
    
async/await
  • 基于 Promise 的语法糖,使异步代码更接近同步写法。
    async function example() {let result = await new Promise((resolve, reject) => {setTimeout(() => resolve("第一步完成"), 1000);});console.log(result);result = await new Promise((resolve, reject) => {setTimeout(() => resolve("第二步完成"), 1000);});console.log(result);
    }
    example();
    
TypeScript 的优势

TypeScript 通过类型系统增强了 JavaScript 的异步编程,例如:

  • 类型推断和类型检查。
  • 更安全的 Promise 和 async/await 使用。
    async function fetchData(): Promise<string> {const response = await fetch("https://api.example.com/data");return await response.json();
    }
    

2. React 中的异步编程

React 本身不直接处理异步逻辑,但通常与 JavaScript 的异步特性结合使用:

在函数组件中使用 useEffect
import React, { useEffect, useState } from "react";function DataComponent() {const [data, setData] = useState(null);useEffect(() => {async function fetchData() {const response = await fetch("https://api.example.com/data");const result = await response.json();setData(result);}fetchData();}, []);return <div>{data ? data.message : "Loading..."}</div>;
}
在类组件中使用生命周期方法
class DataComponent extends React.Component {state = { data: null };async componentDidMount() {const response = await fetch("https://api.example.com/data");const result = await response.json();this.setState({ data: result });}render() {return <div>{this.state.data ? this.state.data.message : "Loading..."}</div>;}
}

3. Next.js 中的异步编程

Next.js 是基于 React 的框架,支持服务端渲染(SSR)和静态生成(SSG)。异步操作通常在以下场景中使用:

在 API 路由中处理异步
// pages/api/data.js
export default async function handler(req, res) {const response = await fetch("https://api.example.com/data");const data = await response.json();res.status(200).json(data);
}
在页面中获取异步数据
// pages/index.js
export async function getServerSideProps() {const res = await fetch("https://api.example.com/data");const data = await res.json();return {props: { data }, // 将数据传递给页面};
}function Home({ data }) {return <div>{data.message}</div>;
}

4. Python 的 FastAPI 中的异步编程

FastAPI 支持异步请求处理,通过 async def 定义异步路由函数:

定义异步 API 路由
from fastapi import FastAPI
import httpxapp = FastAPI()@app.get("/async-data")
async def get_async_data():async with httpx.AsyncClient() as client:response = await client.get("https://api.example.com/data")return response.json()
并发请求示例
from fastapi import FastAPI
import httpx
import asyncioapp = FastAPI()@app.get("/parallel")
async def parallel_requests():async with httpx.AsyncClient() as client:tasks = [client.get("https://api.example.com/data1"),client.get("https://api.example.com/data2"),]results = await asyncio.gather(*tasks)return [result.json() for result in results]

5. Java 的 Spring Boot 中的异步编程

Spring Boot 通过 @Async 注解实现异步方法调用:

启用异步支持
@SpringBootApplication
@EnableAsync
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
}
定义异步方法
@Service
public class AsyncService {@Asyncpublic void asyncTask() {try {Thread.sleep(1000); // 模拟耗时操作System.out.println("Async task completed");} catch (InterruptedException e) {e.printStackTrace();}}
}
调用异步方法
@RestController
public class AsyncController {@Autowiredprivate AsyncService asyncService;@GetMapping("/start")public String startAsync() {asyncService.asyncTask();return "Async task started";}
}

6. axios 技术及使用方法

axios 是一个基于 Promise 的 HTTP 客户端,支持浏览器和 Node.js 环境,常用于发起异步 HTTP 请求。

安装 axios
npm install axios
基本用法
import axios from "axios";// GET 请求
axios.get("https://api.example.com/data").then(response => {console.log(response.data);}).catch(error => {console.error("Error fetching data:", error);});// POST 请求
axios.post("https://api.example.com/submit", {key1: "value1",key2: "value2"
}).then(response => {console.log("Submission successful:", response.data);}).catch(error => {console.error("Submission failed:", error);});
使用 async/await
async function fetchData() {try {const response = await axios.get("https://api.example.com/data");console.log(response.data);} catch (error) {console.error("Error fetching data:", error);}
}async function submitData() {try {const response = await axios.post("https://api.example.com/submit", {key1: "value1",key2: "value2"});console.log("Submission successful:", response.data);} catch (error) {console.error("Submission failed:", error);}
}
配置 axios 实例
const instance = axios.create({baseURL: "https://api.example.com",timeout: 5000,headers: {"Authorization": "Bearer your_token_here"}
});// 使用配置的实例发起请求
instance.get("/data").then(response => console.log(response.data)).catch(error => console.error(error));
拦截器(Interceptors)
// 请求拦截器
axios.interceptors.request.use(config => {console.log("Request sent:", config);return config;
}, error => {return Promise.reject(error);
});// 响应拦截器
axios.interceptors.response.use(response => {console.log("Response received:", response);return response;
}, error => {return Promise.reject(error);
});

总结

技术栈异步实现方式
JavaScript/TypeScript回调函数、Promise、async/await
ReactuseEffect + async/await 或生命周期方法
Next.jsAPI 路由中的异步处理、getServerSideProps
FastAPIasync def 定义异步路由、httpx 库发起异步请求
Spring Boot@Async 注解、线程池配置
axios基于 Promise 的 HTTP 客户端,支持 GET/POST 等请求及拦截器、异步/await 写法

异步编程的核心目标是提高程序的并发性和响应性,具体实现方式因技术栈而异,但底层逻辑(如事件循环、非阻塞 I/O)通常相似。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词