老师,同样是回调函数,为什么唯独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>
问题描述:
then里面的回调出现了延时器的效果,会优先执行代码中其他部分,最后执行then里面的回调函数,为什么呢?
2回答
同学你好,定时器也是会这样的,例如:
控制台:
祝学习愉快~
好帮手慕言
2021-07-03
同学你好,promise的then方法是异步的,所以会先打印n的值,后打印then函数中的代码。
祝学习愉快~
相似问题