async和await关键字
async:表示函数是异步执行,
await:表示当前函数先执行,执行完之后,再执行其他函数
await用于等待一个promise对象,它只能在async函数中使用.
async函数,会返回一个Promise对象,可以用.then调用async函数中return的结果
async function func1(){
return "hello async."
}
func1().then(res => {
console.log(res)
})

async function func1(){
return "hello async."
}
func1().then(res=>{
console.log(res)
})
console.log('aaaaaaaaaaaaaa')

async函数中,可以使用await表达式,async函数执行,遇到await,会先暂停,等到await后的异步执行完毕,再继续往后执行.
await是基于Promise一起使用的
// 1.使用await
function testAwait() {
return new Promise((resolve) => {
setTimeout(function () {
console.log("异步中的输出");
resolve();
}, 1000);
});
}
async function helloAsync() {
await testAwait(); // 等待异步
console.log("async中的输出");
}
helloAsync(); // 输出:先输出"异步中的输出",再输出"async中的输出"
// 2.不使用await
function testAwait() {
return new Promise((resolve) => {
setTimeout(function () {
console.log("异步中的输出");
resolve();
}, 1000);
});
}
async function helloAsync() {
testAwait();
console.log("async中的输出");
}
helloAsync(); // 输出:先输出"async中的输出",再输出"异步中的输出"
异步网络请求
async function getData(){
const data = axios.get('http://123.207.32.32:8000/home/multidata')
console.log(data)
}
getData()

async function getData(){
const data = await axios.get('http://123.207.32.32:8000/home/multidata')
console.log(data)
}
getData()

第一个任务执行完之后才会执行第二个任务

使用Promise.all效率更高

async/await和promise的关系
async/await ,和promise都可以异步编程
async/await相辅相成,
async函数返回的是promise实例对象
await后面可以跟promise函数
await相当于promise.then方法,并且只是成功的方法resolve,只是await时直接得到一个值,then需要传值进行回调
async await与Promise一样,是非阻塞的。
async await是基于Promise实现的,可以说是改良版的Promise,它不能用于普通的回调函数。
await
await后面跟的不是promise对象,会将其他值包装成一个promise对象
async categoryList(){ let result = await reqCategoryList(); console.log(result) //无需写.then()方法了 }
返回:


浙公网安备 33010602011771号