Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

waiting a function to complete

Tags:

javascript

I have 2 functions. The second one is faster than the first one,how could the function wait to complete first one's work?

function1(); // slow 

function2(); // fast
like image 785
Dorukcan Kişin Avatar asked Dec 27 '25 16:12

Dorukcan Kişin


1 Answers

JavaScript is imperative and single-threaded, it just works like this. function2() won't start until function1() finishes.

If by slow you mean calling asynchronously some external service via AJAX, then we're talking. function1() must provide some sort of callback so that when asynchronous request finishes, function2() is called:

function1(function2);

The implementation is trivial, e.g. using jQuery:

function function1(callback) {
  $.ajax({url: 'some-url'}).done(callback);
}
like image 118
Tomasz Nurkiewicz Avatar answered Dec 30 '25 04:12

Tomasz Nurkiewicz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!