2024-05-06 javascript事件循環(huán)的理解

來直接看面試題 示例代碼如下:

<!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>Promise跟setTimeout練習(xí)</title>
</head>

<body>
    <script type="text/javascript">
        console.log("==========start_main===========")
        setTimeout(() => {
            console.log("主線程最先開始的setTimeout")
            promise3.then(tip => {
                console.log('主線程最先開始的setTimeout——promise3', tip);
            })
        });
        const promise = new Promise((resolve, reject) => {
            console.log("執(zhí)行1")
            //resolve("resol同步執(zhí)行1_resolve參數(shù)——settimeout_out")
            setTimeout(() => {
                console.log("宏任務(wù)里面返回微任務(wù) fuilled狀態(tài)2")
                resolve("resol同步執(zhí)行1_resolve參數(shù)——settimeout")
            })
        })
        promise.then((result) => {
            console.log("result結(jié)果執(zhí)行3",result)
        })

        const promise2 = new Promise(resolve => {
            console.log('同步執(zhí)行2');
            resolve('同步執(zhí)行2_resolve參數(shù)');
        }).then(tip => {
            //console.log('then2_1', tip);
            console.log("執(zhí)行2")
            return 'then2_1'+tip
        }).then(tip => {
            //console.log('then2_2', tip);
            console.log("執(zhí)行4")
        }).then(tip =>{
            //console.log('then2_3', tip);
            console.log("執(zhí)行6")
        })

        setTimeout(() => {
            console.log("setTimeout執(zhí)行")
            promise2.then(tip => {
                console.log('setTimeout執(zhí)行_then2_3', tip);
            })
        });

        const promise3 = new Promise(resolve => {
            console.log('同步執(zhí)行3');
            resolve('同步執(zhí)行3——resolve');
        }).then(tip => {
            //console.log('then3_1', tip);
            console.log("執(zhí)行3")
            return tip+"-return"
        }).then(tip => {
            //console.log('then3_2', tip);
            console.log("執(zhí)行5")
        }).then((tip)=>{
            //console.log('then3_3', tip);
            console.log("執(zhí)行7")
        })

        setTimeout(() => {
            console.log("主線程里面的setTimeout")
            promise3.then(tip => {
                console.log('then3_3', tip);
            })
        });
        console.log("==========start_main_end===========")
    </script>
</body>

</html>

運(yùn)行效果如下


輸出結(jié)果.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容