介绍
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/awaitasync function requestSomething() {console.log(111);// 这时something会等到异步请求的结果回来后才进行赋值,同时不会执行之后的代码const something = await getSomething();console.log(something)console.log(333);}requestSomething() //这个时候会输出 111,222,333