setTimeout模拟请求,使用async和await改写的一些注意地方

https://blog.csdn.net/weixin_41033048/article/details/114979233

 

通过定时器模拟异步数据请求并引入promise处理的方法过程。
一、依次输出1,2,3

setTimeout(() => {
console.log(1);
setTimeout(() => {
console.log(2);
setTimeout(() => {
console.log(3);
}, 1000);
}, 1000);
}, 1000);
1
2
3
4
5
6
7
8
9
二、通过promise处理这些请求

new Promise((res, rej) => {
setTimeout(() => {
res();
}, 1000);
}).then(() => {
console.log(1);
return new Promise((res, rej) => {
setTimeout(() => {
res();
}, 1000);
})
}).then(() => {
console.log(2);
return new Promise((res, rej) => {
setTimeout(() => {
res();
}, 1000);
})
}).then(() => {
console.log(3);
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
三、很关键的一步,使用async 和 await来改装很长的.then()调用链

( async ()=>{
await new Promise((res,rej)=>{
setTimeout(() => {
console.log(1);
}, 1000);
})
await new Promise((res,rej)=>{
setTimeout(() => {
console.log(2);
}, 1000);
})
await new Promise((res,rej)=>{
setTimeout(() => {
console.log(3);
}, 1000);
})
})()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
在这里突然发现,只输出了一个1, 打开调试工具后台,发现执行完了一个就停止往下走了,思索原因就是,await等待的是promise执行的返回值resolve()或者是reject();因此await必须接new Promise,而 new Promise必须也要调用resolve()将内部返回出去。

第三步正确写法:

(async () => {
await new Promise((res, rej) => {
setTimeout(() => {
console.log(1);
res();
}, 1000);
})
await new Promise((res, rej) => {
setTimeout(() => {
console.log(2);
res();
}, 1000);
})
await new Promise((res, rej) => {
setTimeout(() => {
console.log(3);
res();
}, 1000);
})
})()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
四、我们可以不可以抽离相同部分呢,答案是可以的

function time(res, step) {
setTimeout(() => {
console.log(step);
res();
}, 1000);
}

(async () => {
await new Promise((res, rej) => {
time(res, 1);
})
await new Promise((res, rej) => {
time(res, 2);
})
await new Promise((res, rej) => {
time(res, 3);
})
})()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
这里也要注意,我们需要把resolve()调用写在里面。await需要接收这一个函数返回值。

补充一个请求有互相调用关系的例子

var total = 0;

setTimeout(() => {
total = total + 1;
setTimeout(() => {
total = total + 2;
setTimeout(() => {
total = total + 3;
console.log('总数为:', total) //6
}, 1000);
}, 1000);
}, 1000);

1
2
3
4
5
6
7
8
9
10
11
12
13
使用aync和await改造的写法

var total = 0;

(
async () => {
let acount = await new Promise((res, rej) => {
setTimeout(() => {
total = total + 1;
res(total);
}, 1000);
})
let acount2 = await new Promise((res, rej) => {
setTimeout(() => {
total = acount + 2;
res(total);
}, 1000);
})
let acount3 = await new Promise((res, rej) => {
setTimeout(() => {
total = acount2 + 3;
res(total)
}, 1000);
})
console.log('总数为:', acount3)//6
}
)();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
总结:

async和await实现的步骤

使用立即执行函数
在立即执行的函数内前面添加async
await负责接收promise数据类型的返回,所以内部必须要有resolve的返回
如果resolve有参数传送,那么可以在await的外部接收这个参数
参数可以用以后续的处理。
————————————————
版权声明:本文为CSDN博主「叶川飞流」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_41033048/article/details/114979233

posted @ 2022-07-06 16:31  China Soft  阅读(662)  评论(0编辑  收藏  举报