Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sequencing function calls in javascript - are callbacks the only way?

I read through various threads like this one for example.

But it really escapes me how to accomplish the following:

I have 4 functions, and want them happen one after another in sequence. Notice they are in incorrect order, to get my point across. I want the result that will output "1, 2, 3, 4'

function firstFunction(){
  // some very time consuming asynchronous code...
  console.log('1');
}
function thirdFunction(){
  // definitely dont wanna do this until secondFunction is finished
  console.log('3');
}
function secondFunction(){
  // waits for firstFunction to be completed
  console.log('2');
}
function fourthFunction(){
  // last function, not executed until the other 3 are done.
  console.log('4');
}

I tried to figure out callbacks but am getting lost :(

Isn't there some simple way to do this? Like looping through an array...

like image 248
tim Avatar asked Sep 05 '12 03:09

tim


People also ask

What can I use instead of callbacks?

Both callbacks and promises help make our code asynchronous. Making callbacks async can cause issues such as callback hell, so to avoid this we can use promises instead, doing this helps us avoid this pitfall while keeping our code async and neat.

What are callbacks in JavaScript?

A callback is a function passed as an argument to another function. This technique allows a function to call another function. A callback function can run after another function has finished.

Why are callbacks used in JavaScript?

A callback's primary purpose is to execute code in response to an event. These events might be user-initiated, such as mouse clicks or typing. With a callback, you may instruct your application to "execute this code every time the user clicks a key on the keyboard." button.

How do callback functions work in JavaScript?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. The above example is a synchronous callback, as it is executed immediately.

Why are callbacks called callbacks?

A Callback is a function that is to be executed after another function has finished executing — hence the name 'call back'.

Is callback function asynchronous?

A callback is just a function that's passed into another function, with the expectation that the callback will be called at the appropriate time. As we just saw, callbacks used to be the main way asynchronous functions were implemented in JavaScript.

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

If we have three synchronous functions, we can execute them asynchronously using the setTimeout function. setTimeout(doSomething, 10); setTimeout(doSomethingElse, 10); setTimeout(doSomethingUsefulThisTime, 10);

How does callback function work?

Callback Functions A callback function is a function that is passed as an argument to another function, to be “called back” at a later time. A function that accepts other functions as arguments is called a higher-order function, which contains the logic for when the callback function gets executed.

Which of the following is a true statement for JavaScript callbacks?

Which of the following is a true statement for JavaScript callbacks? All except None. Some callbacks are just events, called to give the user a chance to react when a certain state is triggered. A callback is a plain JavaScript function passed to some method as an argument or option.

What is a callback function in node JS?

A callback is a function which is called when a task is completed, thus helps in preventing any kind of blocking and a callback function allows other code to run in the meantime. Callback is called when task get completed and is asynchronous equivalent for a function.

Is JavaScript asynchronous by default?

JavaScript is synchronous by default and is single threaded. This means that code cannot create new threads and it will execute your code block by order after hoisting.


2 Answers

It's a great chance to start using jQuery Deferred.

Apart from the callbacks-based solution the code is readable, flexible and highly maintainable

http://jsfiddle.net/zerkms/zJhph/

function firstFunction(){
  var d = $.Deferred();
  // some very time consuming asynchronous code...
  setTimeout(function() {
    console.log('1');
    d.resolve();
  }, 1000);
  return d.promise();
}
function thirdFunction(){
  var d = $.Deferred();
  // definitely dont wanna do this until secondFunction is finished
  setTimeout(function() {
    console.log('3');
    d.resolve();
  }, 1000);
  return d.promise();
}
function secondFunction(){
  var d = $.Deferred();
  setTimeout(function() {
    console.log('2');
    d.resolve();
  }, 1000);
  return d.promise();
}
function fourthFunction(){
  var d = $.Deferred();
  // last function, not executed until the other 3 are done.
  setTimeout(function() {
    console.log('4');
    d.resolve();
  }, 1000);
  return d.promise();
}

firstFunction().pipe(secondFunction).pipe(thirdFunction).pipe(fourthFunction);​

PS: as an example of asynchronous code I've used setTimeout. The main thing is that in the end of the asynchronous part you need to call d.resolve() to continue chaining methods.

Further reading: http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/

like image 120
zerkms Avatar answered Oct 06 '22 02:10

zerkms


The idea is you'd do something like the following so that once the first function was done running, it'd know what to run as opposed to you having to figure it out on your own outside the function:

function firstFunction(callback){
  // some very time consuming asynchronous code...
  console.log('1');

  return callback(function(){
    alert("Second function finished.");
    return true;
  });
}
function secondFunction(callback){
  // waits for firstFunction to be completed
  console.log('2');

  return callback();
}

firstFunction(secondFunction);

Also look up .apply() and .call().

like image 44
jeremy Avatar answered Oct 06 '22 02:10

jeremy