当前位置: 首页 > news >正文

异步编程与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)通常相似。

相关文章:

  • [Excel VBA]如何製作買三送一優惠條件的POS結帳介面?
  • [特殊字符] UI-Trans:字节跳动发布的多模态 UI 转换大模型工具,重塑界面智能化未来
  • 基于云的内容中台核心优势是什么?
  • [Linux]如何配置mailutils郵件服務?
  • 云原生安全基石:Linux进程隔离技术详解
  • 基于Python的分布式网络爬虫系统设计与实现
  • 在 UVM验证环境中,统计 AXI协议的Outstanding Transactions
  • TDengine 对接微软 SSRS 报表系统
  • 《分布式年夜》解析
  • 容器与编排入门 - SRE 须知的 Docker 与 Kubernetes 基础
  • 力扣 74.搜索二维矩阵
  • ETL工具:Kettle,DataX,Flume,(Kafka)对比辨析
  • 【Linux】深刻理解OS管理
  • 电路图识图基础知识-回路编号及代号(四)
  • ​​UniBoard:私有化部署,导航笔记文件一站式管理
  • 使用自签名证书签名exe程序
  • 想一想android桌面的未读计数角标应该如何设计呢?
  • 【每日一题 | 2025年5.19 ~ 5.25】动态规划相关题
  • Lua5.4.2常用API整理记录
  • static详解
  • ppt免费下载模板网站/网络营销怎么做
  • 吃的网站要怎么做/如何找做网站的公司
  • 营销型网站制作服务商/传媒网站
  • 国外做的好的医疗网站设计/网站维护
  • 网站多久才能做起来/让手机变流畅的软件下载
  • 网站怎么加载图片做logo/人工智能的关键词