1. 程式人生 > 實用技巧 >前端筆試題之同步非同步

前端筆試題之同步非同步

這是程式碼:

//函式1
async function async1() {
    console.log("async1 start");
    await async2();
    console.log("async1 end");

}

//函式2
async  function async2() {
    console.log( 'async2');
}

console.log("script start");

setTimeout(function () {
    console.log("settimeout");
},0);

async1();

new Promise(function (resolve) {
    console.log(
"promise1"); resolve(); }).then(function () { console.log("promise2"); }); console.log('script end');

輸出結果:

執行順序:

//函式1
async function async1() {
    console.log("async1 start");//3、然後進入函式按順序執行
    await async2();//4、呼叫async2()函式
    console.log("async1 end");//8、第二遍執行到這裡

}

//函式2
async  function async2() {
    console.log( 
'async2');//5、被呼叫然後執行 } console.log("script start");//1、頁面按順序從上往下執行 第一個列印 setTimeout(function () { console.log("settimeout");//10、最後執行非同步定時器 就算定時器設定為0它也是非同步的 所有最後呼叫 },0); async1();//2、然後執行到這裡會呼叫函式 new Promise(function (resolve) { console.log("promise1");//6、執行到new建立的Promise函式 是同步的執行 resolve(); }).then(function () { console.log(
"promise2");//9、第二遍按照順序執行到這裡 }); console.log('script end');//7、然後順序執行到這裡開始非同步第二遍順序