Promise --- 面试

1.打印顺序

例1:

<!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>
        setTimeout(()=>{
            console.log(1);
        },0);

        Promise.resolve().then(()=>{
            console.log(2);
        });

        Promise.resolve().then(()=>{
            console.log(3);
        });

        console.log(4);
    </script>
</body>
</html>

打印结果: 4 2 3 1;

分析:先执行 同步请求 再执行 异步请求 ;异步请求分为 宏任务 微任务 ,执行 异步请求 时先执行 微任务 再执行 宏任务

例2:

<!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>
        setTimeout(()=>{
            console.log(1);
        },0);

        new Promise((resolve)=>{
            console.log(2);
            resolve();
        }).then(()=>{
            console.log(3);
        }).then(()=>{
            console.log(4);
        })

        console.log(5);

        //2 5 3 4 1
    </script>
</body>
</html>

打印结果: 2 5 3 4 1;

分析:先同后异,先微后宏;setTimeout() 和 .then() 里都是执行异步请求;new Promise() 里相当于定义一个函数立即执行,所以执行同步请求先打印 2 5 然后执行异步队列打印 3 4 1;

例3:

<!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>
        const fn=()=>
            new Promise((resolve,reject)=>{
                console.log(1);
                let p= new Promise((resolve,reject)=>{
                    console.log(2);
                    setTimeout(()=>{
                        console.log(3);
                        resolve(4);
                    },0);
                    resolve(5);
                });
                resolve(6);
                p.then((arg)=>{
                    console.log(arg);
                })
            })
            fn().then((arg)=>{
                console.log(arg);
            })
        
        
        console.log(7);

        //1 2 7 5 6 3
    </script>
</body>
</html>

打印结果: 1 2 7 5 6 3;

分析:先同后异,先微后宏;setTimeout() 和 .then() 里都是执行异步请求;new Promise() 里相当于定义一个函数立即执行( 等同于 同步请求 按 顺序执行);setTimeout() 中任务放到宏任务队列中,而 .then() 中任务放到微任务队列中等待,所以按顺序执行同步打印 1 2 7 之后打印异步 5  6 3;

特别注意 setTimeout() 当中的 resolve(4) 没有执行,当 setTimeout() 异步请求执行完时,页面已加载完毕 promise 状态已经确定( 只能有一个状态;以确定 resolve(5) 所以 resolve(4) 不会执行 ); 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值