1.用async修饰的函数是一个异步函数
代码:
async function fn() {}
console.log(fn());
视图;
如果什么都不返回则返回一个成功的状态,相当于:
return Promise.resolve('underfined')
2.await阻塞问题
async function fn1() {
const res = await fn();
console.log(res);
console.log(1);
}
async function fn() {
// return Promise.resolve("underfined");
}
fn1();
分析上方的代码:
fn 是被async修饰的函数,是一个异步函数。
fn1里面通过async修饰,通过await调用。
错误的答案:
先输出1 underfined
我们转换下代码:
fn().then((res) => {
console.log(res);
console.log(1);
});
正确的答案:
3.怎么理解阻塞这个概念呢?
我们通过上述的代码我们表面上认为:
通过转换:
我们发现 :
fn().then((res) => {
console.log(res);
console.log(1);
});
是用then包起来的,表面上是同步实则是异步
我们也总结条规律:
async function fn1() {
await fn()
console.log(1);
await fn2()
console.log(2);
await fn3()
console.log(3);
}
async function fn() {
// return Promise.resolve("underfined");
}
async function fn2() {
// return Promise.resolve("underfined");
}
async function fn3() {
// return Promise.resolve("underfined");
}
fn1();
先转换成then的形式:
fn().then(() => {
console.log(1);
});
fn2().then(() => {
console.log(2);
});
fn3().then(() => {
console.log(3);
});
如:
总结:
await阻塞,要等到状态返回才执行下面的代码。表示上看是同步实则是异步的。