1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > axios 进行同步请求(async+await)

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

时间:2019-02-13 20:36:15

相关推荐

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

介绍

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

像这样:

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

async/await是一种建立在Promise之上的编写异步或非阻塞代码的新方法。async是异步的意思,而awaitasync 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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。