neilrudds
neilrudds

Reputation: 215

Javascript function in asp.net

Ok, having an issue withe the return value of a function always returning "undefined"

Heres my code:

//called here:
var res = comms(GENSET_SN);

//the function
function comms(genserial) {
     var Result; 
     //Webservice called here
     MyServices.getCommsState(genserial, "S1", OnComplete1);

     function OnComplete1(args) {
          var Res = eval("(" + args + ")");

          if (Res == 1) {
               Result = 1;
          } else {
                Result = 0;
          }
      }
      return Result;
}

please help!!

Upvotes: 0

Views: 60

Answers (3)

Richard Dalton
Richard Dalton

Reputation: 35793

I'm guessing MyServices.getCommsState(genserial, "S1", OnComplete1); is an ajax request?

If so, the value of Result will be returned before it is actually set in the OnComplete1 callback, hence undefined.

You will need to pass in a callback function containing the code that will use the Result value.

You can change the code to do this instead, note that you pass in the function to comms and then call it in OnComplete1:

comms(GENSET_SN, function(res) {
    // do whatever you need with res here!
});

//the function
function comms(genserial, callback) {
     //Webservice called here
     MyServices.getCommsState(genserial, "S1", function(args) {
         var Res = eval("(" + args + ")"); // I would change this aswell, dont use eval!
         callback(Res == 1 ? 1 : 0);
     });            
}

Upvotes: 1

Joe
Joe

Reputation: 82634

JavaScript is Asynchronous

                function OnComplete1(args) {

                    var Res = eval("(" + args + ")");

                    if (Res == 1) {
                        Result = 1;
                    }
                    else {
                        Result = 0;
                    }
                }
                return Result;

needs to be

              function OnComplete1(args) {

                    var Res = eval("(" + args + ")");

                    if (Res == 1) {
                        Result = 1;
                    }
                    else {
                        Result = 0;
                    }

                    // RIGHT NOW - do something with result
               }

Notes:

1 ) eval just isn't good. Modern browsers have JSON already defined or json2.js is widely available

2 ) You might have caught this error if you formatted you code better:

function OnComplete1(args) {
    var Res = JSON.parse(args);

    if (Res == 1) {
        Result = 1;
    }
    else {
        Result = 0;
    }
}
return Result;

Upvotes: 0

musefan
musefan

Reputation: 48425

Simple. You are not defining the value of Result before the function is returned. I assum getCommsState is an async function. If you need this "wrapper" function (comms) I would suggest adding a callback parameter for this too.

Upvotes: 1

Related Questions