老师,同样是回调函数,为什么唯独then里面的回调会出现延迟执行呢?

来源:3-2 选择练习

__Promise

2021-07-03 12:33:47

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>

<body>
<script>
// 其他回调函数,按顺序执行,最后执行输出n
const arr = [1, 2, 3];
arr.forEach((a, b, c) => {
console.log(a, b, c);
})
const n = 0
console.log(n);

// then中的回调函数,先输出外面的n再执行回调,有点像延时器的效果
const pro1 = new Promise((resolve, reject) => {
resolve()
})

pro1.then(() => {
console.log('pro1完成执行完成了');
}, () => {
console.log('pro1错误执行了');
})

console.log(n);
</script>
</body>

</html>

问题描述:

http://img.mukewang.com/climg/60dfe85d09bd4d2205430250.jpg

then里面的回调出现了延时器的效果,会优先执行代码中其他部分,最后执行then里面的回调函数,为什么呢?​

写回答

2回答

好帮手慕言

2021-07-03

同学你好,定时器也是会这样的,例如:

http://img.mukewang.com/climg/60e044280948a03304200200.jpg

控制台:

http://img.mukewang.com/climg/60e044340940b46304800192.jpg

祝学习愉快~

0

好帮手慕言

2021-07-03

同学你好,promise的then方法是异步的,所以会先打印n的值,后打印then函数中的代码。

祝学习愉快~

0
h_Promise
hp>老师,只有then里的回调会这样吗?我试了下其他回调函数都是按顺序执行的,比如forEach

h021-07-03
共1条回复

0 学习 · 17877 问题

查看课程