MCU單晶片韌體設計

2021年10月21日 星期四

[JavaScript] ES7的async/await 非同步



前端瀏覽器執行JavaScript ,都是採"同步" (即函式執行完,才會往下執行它的下一行程式碼)。



若要採用非同步(Asynchronous)方式執行,可以在函數前面加入async 關鍵詞,如 async init () ,可以使函式init() 具有非同步的處理能力,即init()函內可以包含有需要等待的工作敍述,對需要等待的工作可以在該敍述前,加上await 關鍵字。





<case 左方程式區塊 >
程式呼叫了init()函式, 而在init()函式內因為遇到了await a() 這一行,故init() 會直接返回,去執行console.log('3'), 而原本await a() 的下一行, 會一直等到  a() 函式執行結束後才會開始執行。

因為await, 所以await a() 的下一行 是在未來某個時間點才又繼續執行,這就是非同步函數呼叫的概念。


<case 右方程式區塊 >

雖然 async init()  是一個可以允許非同步執行的函數,但這種寫法then()=> { },會使得console.log(3), 會在init()函式執行完才會執行。 



<!DOCTYPE html>
<html>
<body>

<h2>JavaScript async / await</h2>

<h1 id="demo"></h1>

<script>

async function myDisplay() {

      console.log('1')
    console.log('2')

  console.log('3')
}

myDisplay();
console.log('4')
console.log('5')
</script>

</body>
</html>

輸出為 ==> 1 2 3 4 5


<script>

async function myDisplay() {

      console.log('1')
       await console.log('2')

        console.log('3')
}


</script>

輸出為 ==> 1 2 4 5 3


<script>

async function myDisplay() {

await console.log('1')
await console.log('2')

  console.log('3')
}

myDisplay();
console.log('4')
console.log('5')
</script>

</body>
</html>

輸出為 ==> 1 4 5 2 3