简体   繁体   中英

Javascript. Order of execution of asynchronous functions

Just now I had a discussion with my team-lead, and I have some doubts about his words, looking for professionals' help.

For example, we have three async functions

const fetchViewers = async () => { 
   const viewers = await fetch(...);
   this.setState({ viewers });
};
const fetchPolls = async () => {
   const polls = await fetch(...);
   this.setState({ polls });
};
const fetchRegistrants = async () => {
   const registrants = await fetch(...);
   this.setState({ registrants })
};

And we are invoking them in such order

const init = () => {
   fetchViewers();
   fetchPolls();
   fetchRegistrants();
}

And let's say that fetching viewers takes far more time than two others, my question, is there any reason to put fetchViewers last? Since we are not waiting for them to be resolved in the init function, I'm pretty sure that it doesn't matter because it only affects the order it will be put in the stack, and the calls will be made by the DOM. If it does matter, please explain more detailed why.

Asynchronous functions still run synchronously till the first await . Therefore if you do some long running preparations before the actual asynchronous action, the order does matter. Also if the asynchronous task is accessing a shared ressource (eg they are locking the same database, for example) the order could influence how well the tasks can run in parallel (this is outside JS' scope though). In the case given however I can't really see synchronous code / a shared ressource (except for bandwith, but that should hardly matter), so it should not matter . To give an absolute answer, shuffle the calls (6 combinations, so that's not that much work) and measure it .

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