0

Can JavaScript execute two asynchronous functions or callbacks at the same time? Or does it execute the first one and wait until it is finished then executes the other?

For example, let's say I made two requests and the two returns the response at the same time will JavaScript executes the two functions handleResponse1 and handleResponse2 at the same time.

async function handleResponse1 () {/* some code */}
async function handleResponse2 () {/* some code */}

fetch('https://github.com').then(handleResponse1);
fetch('https://stackoverflow.com').then(handleResponse2);

Another example is if my express server receives three requests for three different endpoints (/users, /courses and /products) at the same time will JavaScript executes getUsers, getCourses and getProducts at the same time.

async function getUsers () {/* some code*/}
async function getCourses () {/* some code*/}
async function getProducts () {/* some code*/}

app.get('/users', getUsers);
app.get('/courses', getCourses);
app.get('/products', getProducts);

The last example is if I read a file and Nodejs returns its data at the same that my express server receives a request will JavaScript execute processFileData and processRequestData at the same time.

async function processFileData () {/*some code*/}
async function processRequestData () {/*some code*/}

fs.readFile('/test.txt', 'utf8' , processFileData)
app.get('/some-endpoint', processRequestData);
Amjed Omar
  • 853
  • 2
  • 14
  • 30
  • 1
    "*Can JavaScript execute two asynchronous functions or callbacks at the same time?*" [Depends on what exactly those async tasks are](https://stackoverflow.com/a/65836893) – VLAZ Oct 29 '21 at 17:39
  • Just if you have more than one agent (e.g. a NodeJS process), which in your case you do not have. – Jonas Wilms Oct 29 '21 at 17:56
  • Asynchronous functions: Yes, concurrently though not in parallel. – Jonas Wilms Oct 29 '21 at 17:57
  • It is the tasks that are active at the same time, not the callbacks for the events that are fired on task completion. – Bergi Oct 29 '21 at 18:26

0 Answers0