Web/06-JavaScript基础:异步编程/13-Promise应用举例.md
2023-05-21 00:11:36 +08:00

30 lines
585 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## 使用 Promise 封装 SetTimeout 定时器
代码举例:
```js
// 方法XX秒后执行指定的代码。这个方法就是在宏任务定时器的执行过程中创建了一个微任务resolve
function delaySeconds(delay = 1000) {
return new Promise((resolve) => setTimeout(resolve, delay));
}
delaySeconds(2000)
.then(() => {
console.log('qiangu');
return delaySeconds(3000);
})
.then(() => {
console.log('yihao');
});
```
打印结果:
```js
// 2秒后打印
qiangu
// 再等3秒后打印
yihao
```