axios 进行同步请求(async+await) 您所在的位置:网站首页 vue异步请求改为同步 axios 进行同步请求(async+await)

axios 进行同步请求(async+await)

2023-04-23 14:15| 来源: 网络整理| 查看: 265

介绍

Axios 是一个基于 promise 的 HTTP 库,它支持 Promise API。

像这样:

axios.post('getsomething').then( res => { // 进行一些操作 } )

而 async/await 是一种建立在Promise之上的编写异步或非阻塞代码的新方法。async 是异步的意思,而 await 是 async wait的简写,即异步等待。

所以从语义上就很好理解 async 用于声明一个 函数 是异步的,而await 用于等待一个异步方法执行完成。

那么想要同步使用数据的话,就可以使用 async+await 。

代码示例

模拟一次异步请求

// 假设这是我们要请求的数据 function getSomething(n) { return new Promise(resolve => { // 模拟1s后返回数据 setTimeout(() => resolve(222), 1000); }); } function requestSomething() { console.log(111); getSomething().then(res => console.log(res)); console.log(333); } requestSomething() //这个时候会输出 111,333,222 // 如果想要等数据返回后再执行后面的代码,那么就要使用 async/await async function requestSomething() { console.log(111); // 这时something会等到异步请求的结果回来后才进行赋值,同时不会执行之后的代码 const something = await getSomething(); console.log(something) console.log(333); } requestSomething() //这个时候会输出 111,222,333介绍

Axios 是一个基于 promise 的 HTTP 库,它支持 Promise API。

像这样:

axios.post('getsomething').then( res => { // 进行一些操作 } )

而 async/await 是一种建立在Promise之上的编写异步或非阻塞代码的新方法。async 是异步的意思,而 await 是 async wait的简写,即异步等待。

所以从语义上就很好理解 async 用于声明一个 函数 是异步的,而await 用于等待一个异步方法执行完成。

那么想要同步使用数据的话,就可以使用 async+await 。

代码示例

模拟一次异步请求

// 假设这是我们要请求的数据 function getSomething(n) { return new Promise(resolve => { // 模拟1s后返回数据 setTimeout(() => resolve(222), 1000); }); } function requestSomething() { console.log(111); getSomething().then(res => console.log(res)); console.log(333); } requestSomething() //这个时候会输出 111,333,222 // 如果想要等数据返回后再执行后面的代码,那么就要使用 async/await async function requestSomething() { console.log(111); // 这时something会等到异步请求的结果回来后才进行赋值,同时不会执行之后的代码 const something = await getSomething(); console.log(something) console.log(333); } requestSomething() //这个时候会输出 111,222,333


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有