前端瀏覽器執行JavaScript ,都是採"同步" (即函式執行完,才會往下執行它的下一行程式碼),若要採用非同步方式執行,可以在函數前面加入async 關鍵詞,如 async init () ,可以使函式init() 內的有些需要等待傳回結果,才能再往下的敘述,透過加上await 關鍵字來完成。此函式於未來某個時間點返回後,才又開始繼續執行下一行。因為await後,此時原呼叫init()的下一行敍述,會開始執行,而不必等待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')
}
myDisplay();
console.log('4')
console.log('5')
</script>
</body>
</html>
輸出為 ==> 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