javascriptasynchronousasync-awaitsynchronization

Why we have to add an 'async' declaration word to the javascript function which call a sync javascript function?


I want to know: why we have to add the word:'async' declaration to the function which call a sync function? Shouldn't it be declared as 'sync'?

Sorry, I am not familiar with 'async/await',and maybe this is only a basic javascript grammar question for someone else.

The below code runs well:'I will output FIRST Even I am in BEHIND' will be outputed first; then,the function 'add()' will output '3' after 2 seconds,out '4' after 5 secs,out '5' after 7 secs,then will the sum 12 immediately at last...

But I am wondering why we have to add a 'async' declaration to the function 'add()'? is this to emphasize that the function itself is an asynchronous function, placed in a piece of JavaScript, it can be executed asynchronously (but its internal execution is synchronous because 'await' keywords happened)?**

If I were to write a JavaScript segment codes that all are executed synchronously, would I have to put all the code into a function declared as asynchronous(like below 'const add = async function')? and do not write any other statements externally (remove the code line: console.log('I will output FIRST Even I am in BEHIND'))?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>async</title>
</head>
<body>

<script type="text/javascript">


    const asy = function (x, time) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve(x)
            }, time)
        })
    }

    const add = async function () {
        const a = await asy(3, 2000)
        console.log(a)
        const b = await asy(4, 5000)
        console.log(b)
        const c = await asy(5, 7000)
        console.log(c)
        const d = a + b + c
        console.log(d)
    }

    add();

    console.log('I will output FIRST Even I am in BEHIND')

</script>


</body>
</html>


Solution

  • You don’t need to put all the code in one function!

    A function should perform only one task assigned to it and return a value. Therefore, asynchronous tasks should be placed in separate functions.

    JavaScript itself is not asynchronous, and the async/await keywords simply inform the interpreter that the result of this code will be obtained later. (Read about the Event Loop).

    If you call an asynchronous function without await, the code will continue to execute without waiting for it to finish. Await tells the interpreter to wait for the completion of this function