I can’t understand In which order will the functions foo and bar be executed?
1- foo and bar will execute in the same time, or 2- foo then bar or 3- bar then foo, I think 1- but I don’t sure
var res = {};
function foo(results) {
res.foo = results;
}
function bar(results) {
res.bar = results;
}
// ajax (..) is some arbitrary function given by a library
ajax( "http://some.url.1", foo );
ajax( "http://some.url.2", bar );
3
Answers
You removed the correct answer from your question in your first edit. It’s: "2- We don’t know"
You can’t know the order without knowing the implementation (or documentation) of
ajax
. The order could even change between different runs.Here is an example:
You can run it multiple times and the order changes. Sometimes it’s
and sometimes it’s
but the functions will never be called at the same time.
JavaScript generally operates on a single event loop. Unless you farm out processing to a Worker you will never have two functions running at the same time.
You haven’t shown us the
ajax
function, but assuming it makes an HTTP callback and then queues the callback function up to be called once the complete HTTP response has arrived:The order will depend on how quickly the server responds to each of the two different HTTP requests and how long it takes for the browser to receive the response.
For example,
http://some.url.1
might cause the server to spend 30 seconds doing a really complete database query before responding, whilehttp://some.url.2
might do something simple that gets a response after 3ms: In which casebar
would be added to the queue beforefoo
and thus run first.We can’t predict the order of the functions foo & bar. These functions depends on ajax request to an api, so whichever ajax request completes first, it will call the corresponding function.
Note: If you need to do synchronize both the functions together, then you can use a promise method.