Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am confused with some topics in javascript.Can anyone explain in detail please.

1. i)In async function can i invoke a function like (calling myName(str) in caller(str) function ) this or i have to use callback?is it worked as synchronously?that means callback(str); will have to wait until myName() completes.

ii)In async function, callback function works synchronously or asynchronously or works after the caller function execution or waiting for callstack(or execution stack) to be empty?

function myName(str){
    console.log('My name is '+str);
}

function yourName(str){
    console.log('Ooo!! Your name is '+str);
}

async function caller(str ,callback)
{
   console.log('async function starts'); 
   
    myName(str);  

    callback(str); 

   console.log('async function compeletes');

}
console.log('JavaScript 1');
caller('Mike',yourName);
console.log('JavaScript 2');

The above code logs:

Javascript 1
async function starts
My name is Mike
Ooo!! Your name is Mike 
async function compeletes
Javascript 2

iii)But I think it should log like below.Because caller() is a async function so it will be executed in background & logged later when current callstack is empty.so it(callstack) will empty after execution of console.log('JavaScript 2').If i wrong how i define which will be log first?what the difference between not using async keyword and using for working as asynchronously?

JavaScript 1
JavaScript 2
async function starts
My name is Mike
Ooo!! Your name is Mike 
async function compeletes

question from:https://stackoverflow.com/questions/66051663/confusion-on-asynchronous-function-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
204 views
Welcome To Ask or Share your Answers For Others

1 Answer

Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...