简体   繁体   中英

JavaScript Asynchronous Function Execution Order

I have a function that makes calls to multiple asynchronous functions.

$("#signUpForm").validator().on("submit", function(event) {
if (event.isDefaultPrevented()) {
    // handle the invalid form...
    sformError();
    ssubmitMSG(false, "Please fill all fields!");
} else {
    // everything looks good!
    event.preventDefault();
    
    //create use when form is submit
    ssubmitForm();
    
    //send email verification
    sendEmailVerification();

    //sign out the user
    signOut();
    
  
}
});

the functions ssubmitForm(), sendEmailVerification() and SignOut() are all declared asynchronous and all have await statements in them.

I am getting weird behavior that seems to signal to me that these three functions are not running in the order they are written in the code. I thought that with asynchronous code all other code pauses execution and waits for the await statement to finish. But from my logs, I neah function it doesn't seem so. Is this behavior only within the scope of the asynchronous function itself? What is the execution order of the three functions? Can sendEmailVerification() be called before ssubmitForm() is done execution?

Also, I'm not sure if I'm using the correct verbiage/vocabulary to describe my problem. This has been a big problem for me as I am not easily able to search for my issues if I don't know the vocab. Please feel free to correct me on any misuse of terminology.

They are started in the order that they are called, but because they are async, they might not run in the order they are called. They return immediately and return an unresolved Promise , which will eventually resolve (or reject) asynchronously when the called function completes.

You need to mark your function async and await each of the calls in turn:

$("#signUpForm").validator().on("submit", async function(event) {
if (event.isDefaultPrevented()) {
    // handle the invalid form...
    sformError();
    ssubmitMSG(false, "Please fill all fields!");
} else {
    // everything looks good!
    event.preventDefault();
    
    //create use when form is submit
    await ssubmitForm();
    
    //send email verification
    await sendEmailVerification();

    //sign out the user
    await signOut();
    
  
}
});

To better understand async / await , I recommend learning about promises first. They are the underlying model that makes everything tick; async / await is just syntactic sugar on top.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM