kosta
kosta

Reputation: 4750

Javascript function execution synchronization

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

Upvotes: 1

Views: 20592

Answers (2)

Martin Jespersen
Martin Jespersen

Reputation: 26183

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/

Upvotes: 3

Mike Christensen
Mike Christensen

Reputation: 91666

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";
}

Upvotes: 0

Related Questions