skip to Main Content

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>

2

Answers


  1. Chosen as BEST ANSWER

    After some research,I found the answer:

    ... However, starting from ECMAScript 2022 (ES13), 'await' can be used at the top level of modules without being placed in asynchronous functions. This means that you can directly use the 'await' keyword at the top level of the module without wrapping it in any function. This is a module specific feature and is not applicable to traditional script files.

    Here is an example demonstrating how to use await at the top level of a module:

    // This is ES moudule.
    import fetch from 'node-fetch';
    
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    
    console.log(data);


  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search