Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Multiple Callback Function

I have been trying to figure out the Callback function feature in Javascript for a while without any success. I probably have the code messed up, however I am not getting any Javascript errors, so I supposed the syntax is somewhat correct.

Basically, I am looking for the getDistanceWithLatLong() function to end before the updateDB() begins, and then make sure that ends before the printList() function begins.

I have it working with a hardcoded "setTimeout" call on the functions, but I am overcompensating and forcing users to wait longer without a need if the Callback stuff would work.

Any suggestions? Below is the code:

function runSearchInOrder(callback) {
    getDistanceWithLatLong(function() {
        updateDB(function() {
            printList(callback);
        });
    });
}
like image 363
Rob Avatar asked May 20 '14 00:05

Rob


People also ask

Can you have two callbacks?

An output can only have a single callback function.

How many callback functions can be executed at any time?

As long as the callback code is purely sync than no two functions can execute parallel.

What is a nested callback?

When using callbacks, you're required to put dependent program logic that is to be executed after an asynchronous operation has completed inside a callback. When you combine multiple such calls, you end up with deeply nested code. Deeply nested callbacks in JavaScript code.

How can you avoid callback Hells?

We can avoid the callback hell with the help of Promises. Promises in javascript are a way to handle asynchronous operations in Node. js. It allows us to return a value from an asynchronous function like synchronous functions.


2 Answers

To accomplish this, you need to pass the next callback into each function.

function printList(callback) {
  // do your printList work
  console.log('printList is done');
  callback();
}

function updateDB(callback) {
  // do your updateDB work
  console.log('updateDB is done');
  callback()
}

function getDistanceWithLatLong(callback) {
  // do your getDistanceWithLatLong work
  console.log('getDistanceWithLatLong is done');
  callback();
}

function runSearchInOrder(callback) {
    getDistanceWithLatLong(function() {
        updateDB(function() {
            printList(callback);
        });
    });
}

runSearchInOrder(function(){console.log('finished')});

This code outputs:

getDistanceWithLatLong is done
updateDB is done
printList is done
finished 
like image 66
Joe Frambach Avatar answered Nov 11 '22 06:11

Joe Frambach


wouldn't this work:

function callback(f1, f2) {
    f1();
    f2();
}

As for passing arguments, be creative.

like image 31
Yamcha Avatar answered Nov 11 '22 07:11

Yamcha