版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_36146776/article/details/89400828
先看一个例子
console.log(1);
async function test() {
console.log(2);
await function () {
setTimeout(()=>{
console.log(3);
})
}
console.log(4);
};
console.log(5);
test();
console.log(6);
输出结果:1,5,2,6,4
async
async确保了函数返回一个promise
console.log(1);
async function f () {
console.log(2)
return 'hello world!'
}
f().then(result=>{
console.log(result);
})
console.log(3);
//1,2,3,'hello,world'
await
await只能在async函数内部使用,await不能工作在顶级作用域
await可以让JavaScript进行等待,直到一个promise执行并返回它的结果,JavaScript才会继续往下执行。
使用举例子
console.log(1);
async function f () {
console.log(2);
let promise = new Promise((resolve, reject) => {
console.log(3);
setTimeout(() => {
resolve('done!')
}, 1000)
})
let result = await promise;
console.log(result);//done
return 5;
}
f().then(result=>{
console.log(result);//5
})
console.log(6);
// 1,2,3,6,[等待1秒],'done',5
错误处理
async function f() {
let response = await fetch('http://no-such-url')
}
// f()变成了一个rejected的promise
f().catch(alert) // TypeError: failed to fetch
async function f() {
throw new Error('Whoops!')
}
有了async/await,我们很少需要写promise.then/catch,但是别忘了它们是基于promise的,
其他:如Promise.all
可以适当的和async和await公用,Promise.all能够同时等待很多任务。
在vue中的应用举例
methods: {
updateMessage: async function () {
this.message = 'updated'
console.log(this.$el.textContent) // => '未更新'
await this.$nextTick()
console.log(this.$el.textContent) // => '已更新'
}
}