Skip to content Skip to sidebar Skip to footer

Javascript Function Not Returning Value

I am calling a function with the following code: var resultz = nsEditor.updateStringCall(debtID, column2Change, value2Change, 4, 10); The function that is being called but doesn't

Solution 1:

The function is not returning a value because the returns in your method are embedded inside callback functions. They are only returning from those callbacks, not from your main function. Consider, for example, your "success" callback:

success: function(response) {
    resultz2 = 1;
    return resultz2;
}

This return is just returning from the success function... It doesn't bubble up to your updateStringCall function.

The reason it has to work this way is because ajax calls are asynchronous. Your method returns immediately while the request happens in the background. So in order to get the return value, you have to pass in a callback that has access to the value when it's ready, and then call the callback from within the ajax callbacks instead of returning a value.

So change your method definition to this:

// Note I added a "callback" parameterfunction(pdebtID, pcolumn2Change, pvalue2Change, pmin, pmax, callback) { ... }

And then in your ajax callbacks, call it instead of returning a value:

success: function(response) {
    resultz2 = 1;
    callback(resultz2);
},
error: function(jqXHR, textStatus, errorThrown) {
    resultz2 = 0;
    callback(resultz2);
});

Finally, pass in a callback when you call this method:

nsEditor.updateStringCall(debtID, column2Change, value2Change, 4, 10, function(resultz) {
    // Do something with resultz
});

One final note, if you are going to have that blanket try/catch in there, you should change that to use the callback also:

catch (e) {
    resultz2 = 0;
    callback(resultz2);
}

But really, I'd recommend just taking that try/catch out altogether. I can't see how that can possibly be helpful here. It will only hide actual problems with code that already has a better structure for error handling. I suspect you just put in there to debug this return problem, but if it was there already, just take it out.

This is the world of event-driven functional programming! It's a very common sort of structure in javascript.

Solution 2:

Ajax calls are asynchronous. You'll have to work with your result from within the success callback of the $.ajax().

Solution 3:

Add async: false like this:

$.ajax({
  type: "POST",
  async: false,
  url: "Components/MintLibraries.cfc",
  dataType: "json",
  cache: false,
})

Post a Comment for "Javascript Function Not Returning Value"