[Solved] How to control which function run first in Javascript [closed]


Javascript is single threaded, whichever function that is called is being executed in that order. The only exception to this rule is how the event loop is being executed.

So a call to setTimeout or setInterval cannot give a real idea on which method will get called first. Even if you use a setTimeout with the same interval. In thoery, the first method should be executed first in the event queue but that might be subject to implementations.

If you want to synchronize evented function, you have a while range of tools and libraries that will just what you need.

The callback method can be used to call a continuation when some kind of work is finished. This pattern has been improved in a more complex datastructure called a Promise.

Promise are pretty much the same things as callbacks but they are syntactically nicer to use.

Callback:

function foo(id, callback){
  //ajax.get('/data/' + id, callback)
  ajax.get('/data/' + id, function (data) {
    callback(data)
  })
}
foo(id, function (data) {
  alert(data)
})

Promise:

function foo(id) {
  return promiseGet('/data' + id)
}
foo(4).then(function (data) {
  alert(data)
})

The advantage of promises is that they can be chained and thus, you can use async apis, pretty much like usually sync apis. All of the “then” parts are going to be executed in the order you added them.

Here’s the site of promisejs that does a quite good explanation of promises.
https://www.promisejs.org/

solved How to control which function run first in Javascript [closed]