How to Call 3 Functions in Order to Execute Them One After the Other

How should I call 3 functions in order to execute them one after the other?

In Javascript, there are synchronous and asynchronous functions.

Synchronous Functions

Most functions in Javascript are synchronous. If you were to call several synchronous functions in a row

doSomething();
doSomethingElse();
doSomethingUsefulThisTime();

they will execute in order. doSomethingElse will not start until doSomething has completed. doSomethingUsefulThisTime, in turn, will not start until doSomethingElse has completed.

Asynchronous Functions

Asynchronous function, however, will not wait for each other. Let us look at the same code sample we had above, this time assuming that the functions are asynchronous

doSomething();
doSomethingElse();
doSomethingUsefulThisTime();

The functions will be initialized in order, but they will all execute roughly at the same time. You can't consistently predict which one will finish first: the one that happens to take the shortest amount of time to execute will finish first.

But sometimes, you want functions that are asynchronous to execute in order, and sometimes you want functions that are synchronous to execute asynchronously. Fortunately, this is possible with callbacks and timeouts, respectively.

Callbacks

Let's assume that we have three asynchronous functions that we want to execute in order, some_3secs_function, some_5secs_function, and some_8secs_function.

Since functions can be passed as arguments in Javascript, you can pass a function as a callback to execute after the function has completed.

If we create the functions like this

function some_3secs_function(value, callback){
//do stuff
callback();
}

then you can call then in order, like this:

some_3secs_function(some_value, function() {
some_5secs_function(other_value, function() {
some_8secs_function(third_value, function() {
//All three functions have completed, in order.
});
});
});

Timeouts

In Javascript, you can tell a function to execute after a certain timeout (in milliseconds). This can, in effect, make synchronous functions behave asynchronously.

If we have three synchronous functions, we can execute them asynchronously using the setTimeout function.

setTimeout(doSomething, 10);
setTimeout(doSomethingElse, 10);
setTimeout(doSomethingUsefulThisTime, 10);

This is, however, a bit ugly and violates the DRY principle[wikipedia]. We could clean this up a bit by creating a function that accepts an array of functions and a timeout.

function executeAsynchronously(functions, timeout) {
for(var i = 0; i < functions.length; i++) {
setTimeout(functions[i], timeout);
}
}

This can be called like so:

executeAsynchronously(
[doSomething, doSomethingElse, doSomethingUsefulThisTime], 10);

In summary, if you have asynchronous functions that you want to execute syncronously, use callbacks, and if you have synchronous functions that you want to execute asynchronously, use timeouts.

Call a function after previous function is complete

Specify an anonymous callback, and make function1 accept it:

$('a.button').click(function(){
if (condition == 'true'){
function1(someVariable, function() {
function2(someOtherVariable);
});
}
else {
doThis(someVariable);
}
});

function function1(param, callback) {
...do stuff
callback();
}

Efficient way of executing 2 functions one after another in Javascript

There are a couple of ways you could approach this, the two most common ways would be using a callback, or using Promises.

Using Callbacks

You would add a callback argument to the first function, and then pass in function two as the callback:

function one(callback) {
setTimeout(function() {
console.log("first function executed");
callback();
}, 3000);
}

function two() {
console.log("second function executed");
}

one(two)

How to execute a Javascript function only after multiple other functions have completed?

If you want to keep it simple, you can use a counter-based callbacks system. Here's a draft of a system that allows when(A, B).then(C) syntax. (when/then is actually just sugar, but then again the whole system arguably is.)

var when = function() {
var args = arguments; // the functions to execute first
return {
then: function(done) {
var counter = 0;
for(var i = 0; i < args.length; i++) {
// call each function with a function to call on done
args[i](function() {
counter++;
if(counter === args.length) { // all functions have notified they're done
done();
}
});
}
}
};
};

Usage:

when(
function(done) {
// do things
done();
},
function(done) {
// do things
setTimeout(done, 1000);
},
...
).then(function() {
// all are done
});

Ensure two functions execute one after the other, where the first function has an asynchronous call inside it

All async functions must accept callbacks (or return a promise). Otherwise it's not possible to execute something after the async function has completed.

So, since a() is async. I'd assume that your example:

var someResult = a();

is a typo. It should be:

a(function(someResult){
// ...
})

There is no way around this. You cannot pause the interpreter and wait for an async function to complete because pausing the interpreter will also pause the event loop causing the async function to never complete.

If a() is properly written, you should be able to just do this:

async.series([
function(callback) {
a(function(someResult){
callback(null, someResult);
});
},
function(callback) {
var someOtherResult = b();
callback(null, someOtherResult);
}
],
function(err, results) {
console.log('Yay');
});

If not, send a() back to the person who wrote it and tell him he's doing it wrong.

How to call multiple JavaScript functions in onclick event?

onclick="doSomething();doSomethingElse();"

But really, you're better off not using onclick at all and attaching the event handler to the DOM node through your Javascript code. This is known as unobtrusive javascript.

How should I execute functions only one after another in JavaScript?

In getCoordinates you use asynchronous request to Google API via geocoder.geocode() call. The second argument in this method is an actual callback which is executed when the request is done. Pass own callback function to getCoordinates function (as a second argument) and call it once the actual request is finished processing.

function getCoordinates(city, callback) {
...

geocoder.geocode({ address: address }, function(results, status) {
...
if (typeof callback === 'function')
callback();
});
}

getCoordinates(cityOneString, function() {
getCoordinates(cityTwoString);
});


Related Topics



Leave a reply



Submit