Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

run another function after preceding function has completed?

Tags:

javascript

if i fire up 2 functions like this:

prepare_data();
read_data();

then i guess they are running at the same time. but as you can see function two is depending on the first one, so how can i make the latter one run after the first one is completed?

like image 242
ajsie Avatar asked May 09 '26 12:05

ajsie


2 Answers

Javascript, and most other languages, run code sequentially.

Therefore, they will not both run at the same time.

In fact, it is not possible to run two different pieces of Javascript code at the same time. However, in many other languages, it is possible using threads.

However, if they make AJAX calls, the corresponding server-side code called by both functions will run simultaneously.
To prevent that, you'll need to make the first function accept a callback parameter and pass it the second function.

like image 134
SLaks Avatar answered May 11 '26 01:05

SLaks


I'm assuming the first call makes some kind of asynchronous call that the second relies upon because otherwise the two functions will execute sequentially.

If so you need to do the second in the callback from the first. For example, in jQuery:

function prepare_data() {
  $("#data").load("/load_data.php", function() {
    read_data();
  });
}

It's impossible to say how you should solve this without more information on whether you're using vanilla Javascript or a particular library. I'd strongly suggest using a library of some sort for AJAX however.

like image 31
cletus Avatar answered May 11 '26 01:05

cletus