课程名称:await 函数用法
课程章节:await 的机制、 await 的值 和 await 的注意事项
课程讲师: Alex
课程内容:
1、 await 的机制
举个例子:
下面的代码是前面学习基础用到的广告代码
.ad{
display: block;
width: 300px;
height: 150px;
margin: 0 auto;
}
.none{
display: none;
}<img src="/ad.jpg" alt="前端体系课" class="ad none" id="ad">
<script>
// 先写一个等待函数
function wait(ms){
return new Promise(resolve => {
setTimeout(resolve,ms);
});
}
async function ad() {
const adDom = document.getElementById('ad');
await wait(1000);
// 显示
adDom.classList.remove('none');
await wait(2000);
// 隐藏
adDom.classList.add('none');
}
ad();
console.log('async外部函数的代码')
</script>上面的 await 部分 相当于
wait(1000).then( ()=> {
// 显示
adDom.classList.remove('none');
return wait(2000)
}).then(()=> {
// 隐藏
adDom.classList.add('none');
})上面的广告和控制台打印,毫无疑问是先打印,再显示广告
由此我们可以得出结论:
① async 函数中的代码有先后关系,await 会阻塞该async 函数中代码的执行,async 函数外的代码不受影响
② async 函数内部是同步执行的,它本身是异步的
2、await 的值
依然是上面的代码
// 先写一个等待函数
function wait(ms){
return new Promise(resolve => {
setTimeout(resolve,ms);
});
}
async function ad() {
const adDom = document.getElementById('ad');
//await wait(1000);
console.log(await wait(1000)); //undefined
adDom.classList.remove('none');
await wait(2000);
// 隐藏
adDom.classList.add('none');
}
ad();这里返回的是 undefined,原因就是等待函数那里的
return new Promise(resolve => {
setTimeout(resolve,ms);
});相当于:
setTimeout(()=>{
resolve(undefined)
},ms)也就是说resolve默认传了个undefined,如果改成123,那么打印的的就是123
所以总结一下:
① 如果 await 后面是一个 Promise 对象,await 的值就是该 Promise 对象的结果(PromiseResult)
当后面不跟Promise时:
无论是什么,都直接打印 await 后面跟的值,因为await后面要跟异步操作,如果什么都没写,那就相当于在后面做了一个包装,而resolve后面的值本身就是直接返回出来的
async function fn(){
// let result = await 123;
let result = await [1,2,3];
//相当于
let result = await Promise.resolve([1,2,3]);
console.log(result) //[1,2,3]
}② 如果await后面不是Promise对象,await的值就是该值,相当于包了一层Promise.resolve() 之后再获取该Promise对象的结果
3、await 的注意事项
function wait(ms,error){
return new Promise((resolve,reject) => {
setTimeout(()=>{
if(!error){
resolve()
}else{
reject(new Error(error))
}
},ms);
});
}
async function ad() {
const adDom = document.getElementById('ad');
// await wait(1000,'等1s失败了');
// 显示
adDom.classList.remove('none');
await wait(2000,'等2s失败了');
// 隐藏
adDom.classList.add('none');
}
ad().then(()=>{
console.log('success');
});由图可知:
async 函数内部所有 await 后面的 Promise 对象都成功,async 函数返回的 Promise 对象才会成功;只要任何一个 await 后面的 Promise 对象失败,那么 async 函数返回的 Promise 对象就会失败
* 可以通过 try...catch 或者 Promise...catch 的方式来处理错误
promise...catch
await 一般只能用在 async 函数中,async 函数中可以没有 await
有的浏览器也可以用在模块的最顶层,借用 await 解决模块异步加载的问题
课程收获:
老师讲的非常细致,通俗易懂。这一节学的是 await 函数的用法,通过学习我了解了什么是 await 函数的返回值、await 函数的机制以及 await函数的注意事项 。知道,await 只能用在 async 函数中,async 并不是一定要和 await 一起用,这是因为有的浏览器也可以用在模块的最顶层,借用 await 解决模块异步加载的问题
,期待明天的学习