1
function test() { /*some business logic*/ return response; } function calculate() { if (test() == true) { console.log("Success"); } else { console.log("Fail"); } } 

my test function is in different js file which does some business processing (processing takes some time) on data and return boolean response.

I am calling test function from calculate function (in different js file). I am expecting console output as 'success'(test function always return true), but it is giving me 'Fail'. But if I debug this code and wait sometimes on '(if(test()==true))' then i get expected output . Basically it is a synchronization issue. How can i solve that?

3
  • JavaScript is async. Without knowing what test() is actually doing people can't help you figure it out. test() is the bit that needs the work. If its making a network request etc you really should look into promises or callbacks instead. JavaScript is single threaded if you hack it up to make a ajax request synchronous you will lock the browser up whilst it waits for the response. Commented Oct 23, 2015 at 7:37
  • 1
    No, javascript is synchronous and single threaded. It's only async when making async reqeusts. Commented Oct 23, 2015 at 8:08
  • Its true Daniel .. javascript is synchronous language .. Actually problem was with the business logic written in test method.. Its has now solved . Thanks Commented Oct 26, 2015 at 8:59

2 Answers 2

1

I try to modify your code little bit to cater for your need which make use of JQuery Deferred object. If you comment out "deferred.reject()", you should get the case when your function is considered as failed.

It would make your function waiting for another function to give a response.

var test = function(){ var deferred = $.Deferred(); setTimeout(function(){ deferred.resolve(); //deferred.reject(); },3000); return deferred.promise(); }; test().done(function(){ console.log("success");}) .fail(function(){ console.log("fail");}) 
Sign up to request clarification or add additional context in comments.

1 Comment

the setTimeout function is just for me to make that function like normal function spending some time to handle the operation
0

I think from the codes above, you would not have any problems to get "Success" route run. It really depends on how does your business logic run. If they are running in asynchronize manner then you should probably using event driven model to run your calculation logic. For example, you register an event via document.addEventListener('testCompleted', caculate()) and then you fire this event in test().

Hope it helps.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.