【Promise】async + await + axios发送Ajax请求(五)

-async函数

  1. 函数的返回值为 promise 对象
  2. promise 对象的结果由 async 函数执行的返回值决定

Ⅱ-await表达式

  1. await 右侧的表达式一般为 promise 对象, 但也可以是其它的值

  2. 如果表达式是 promise 对象, await 返回的是 promise 成功的值

  3. 如果表达式是其它值, 直接将此值作为 await 的返回值

Ⅲ-注意

  1. await 必须写在 async 函数中, 但 async 函数中可以没有 await
  2. 如果 await 的 promise 失败了, 就会抛出异常, 需要通过 try...catch 捕获处理

IV-如何在Promise外部使用Promise的结果

用到的本章节知识:

1、axios本质上就是一个promise,所以下面用定时器+Promise模拟axios,效果一样,可以将new Promise(resolve => {setTimeout(function() { resolve("promise普通结果"); }, 1000); })等价于axios({})

2、resolve() 与reject()是修改Promise状态并往外抛出的,一个Promise只能改变一次状态,所以一个primise中只能调用一次

3、 上一步抛出后可以在下面 的.then()中获取到

Ⅰ-如果没有用.then(),则值会抛往Promise外部

Ⅱ-如果声明了.then(),则值会被.then()接住,放到里面处理,如果需要再次抛出--某些业务场景需要 ,然后在下一个then()或者外部使用, 则可以 .then(v=>return v) ---前提这个链式调用前曾使用过resolve() 与reject()才用return,不然就用这两个resolve() 与reject()

//讲解时写的简单demo
let resolveCommon = ()=> {
 let result="普通promise初始值"
  result=new Promise(resolve => {setTimeout(function() { resolve("promise普通结果"); }, 1000); })
 console.log(result)
 //打印结果: Promise { <pending> } 
};
let resolveAsync=async ()=> {
 let result="await+async的promise初始值"
  result=await new Promise(resolve => { setTimeout(function() { resolve("这是async+await结果"); }, 1000);})
 console.log(result)
 //打印结果: 这是async+await结果  这里就是正确的值,你可以在下一步进行正常使用,也可以用在下一步的promise中
 //------------------------------------------------------
 //在第二个promise中调用使用
 let result2=""
 result2= await new Promise(resolve => { setTimeout(function() { resolve(result+"+经过第二个promise加工"); }, 1000);})
 .then(v=>{
   console.log("第二个promise的then()中打印并返回:",v)
   return v+",经过then()加工返回"
 })
 console.log("最终结果:第二个promise外部结果打印,",result2)
 //---------------------------------------------
};
resolveCommon()  //调用普通promise函数
resolveAsync()    //调用await+async
/**
运行结果
1.resolveCommon() 运行结果:    Promise { <pending> }
2.resolveAsync() 运行结果:     
 这是async+await结果
 第二个promise的then()中打印并返回: 这是async+await结果+经过第二个promise加工
 最终结果:第二个promise外部结果打印, 这是async+await结果+经过第二个promise加工,经过then()加工返回
*/

V-async与await结合发送Ajax请求

//获取元素
				const btn=document.getElementsByTagName('button')
				const result=document.getElementById('result')
				
				
				btn[0].onclick=async function(){
					//get请求
					 const data=await axios.get('http://127.0.0.1:8000/server',{
						//参数
						params:{
							id:100
						},
					})
					
					console.log(data);
				}

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个基于Axios、Vue3和TypeScript的Ajax请求封装示例: ``` import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'; import { reactive } from 'vue'; interface ResponseData { code: number; message: string; data: any; } interface AxiosResult<T> { data: T | null; error: string | null; loading: boolean; } class AjaxService { private instance: AxiosInstance; constructor(baseURL: string) { this.instance = axios.create({ baseURL, timeout: 5000, }); this.instance.interceptors.request.use( (config: AxiosRequestConfig) => { config.headers.Authorization = sessionStorage.getItem('token') || ''; return config; }, (error: any) => { console.error(error); }, ); this.instance.interceptors.response.use( (res: AxiosResponse<ResponseData>) => { if (res.status === 200) { if (res.data.code === 0) { return res.data.data; } else { console.error(res.data.message); return null; } } else { console.error(res.status); return null; } }, (error: any) => { console.error(error); return null; }, ); } public async get<T>(url: string, config?: AxiosRequestConfig): Promise<AxiosResult<T>> { const result: AxiosResult<T> = reactive({ data: null, error: null, loading: true, }); try { const response = await this.instance.get(url, config); result.data = response; } catch (error) { result.error = error; } finally { result.loading = false; } return result; } public async post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResult<T>> { const result: AxiosResult<T> = reactive({ data: null, error: null, loading: true, }); try { const response = await this.instance.post(url, data, config); result.data = response; } catch (error) { result.error = error; } finally { result.loading = false; } return result; } } export default new AjaxService('https://example.com/api'); ``` 使用示例: ``` import ajax from './ajax-service'; const result = await ajax.get<User[]>('/users'); if (result.error) { console.error(result.error); } else if (result.data) { console.log(result.data); } else { console.log('No data returned.'); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值