1

I have three javascript files 1.js, 2.js, 3.js

1.js

function getOne()
{
return "one";
}

2.js

function getTwo()
{
return "two";
}

3.js

getOne(function(resp1)
{
console.log(resp1)
getTwo(function(resp2)
{
console.log(resp2);
}

});

The function calls in 3.js are not executed at all. I load the js files in the order 1.js 2.js 3.js

COuld someone please help

1
  • 2
    getOne doesn't take parameters. How can you possibly expect your callbacks you're passing into them to be called? Commented Mar 4, 2014 at 22:52

2 Answers 2

3

The reason it doesn't work, as already mentioned, is that your methods don't handle the callbacks you pass in as arguments.

To make it work like you want you need to rewrite your methods to look like this:

function getOne(callback)
{
  callback("one");
}

function getTwo(callback)
{
  callback("two");
}

Since you question is about function execution synchronization however, you might wish to go down another path.

What you are doing will work fine for a couple of functions, but when you get to the point where you wish to synchronize many functions you end up with the pyramid of doom where code marches to the right faster than it marches forward.

step1(function (value1) {
    step2(value1, function(value2) {
        step3(value2, function(value3) {
            step4(value3, function(value4) {
                ...continue ad nauseum 
            });
        });
    });
});

In that case you might want to look into futures and promises

You can read more about promise patterns in javascript here:

http://www.html5rocks.com/en/tutorials/es6/promises/

Sign up to request clarification or add additional context in comments.

Comments

0

The code:

getOne(function(resp1)
   {
      console.log(resp1)
      getTwo(function(resp2)
      {
         console.log(resp2);
      }
   }
);

Does in fact call getOne, however it passes in an anonymous function as a parameter. getOne doesn't actually take any parameters (though passing one doesn't hurt, nor cause any errors), nor is that anonymous function actually executed anywhere.

I'm not sure exactly what you're trying to do, but I'd start by giving getOne a parameter:

function getOne(fnFoo)
{
   return "one";
}

You'd then be able to call the function you pass in:

function getOne(fnFoo)
{
   fnFoo();
   return "one";
}

1 Comment

Not sure why the down vote, though maybe I missed the gist of what the code was attempting to do.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.