Return state from another function

I am unable to pass a return state from one function to another. In the first part of code I am calling the printing function in .ajax success method:

  $("#print_button").click(function() {
  var elem = $(this);
  $.ajax({
      url: 'print.php',
      type: 'POST',
      data: "print_id=" + elem.attr('data-print'),
      dataType: 'json',
      method: 'post',
      success: function(data) {
          if (data !== null) {
              //returnState
              if (printnow(data) == true) {
                  console.log("print success");
              } else {
                  console.log("print failed");
              }
          } else {
              alert("no data to print");
          }
      }
  })
  });

The print function in short:

  function printnow(beer) {
      var returnState = false;
      $.get("./servis.label", function(labelXml) {
          try {...
              var success = label.print(printerName);
              if (success == true) {
                  returnState = true;
              } else {
                  returnState = false;
              }
          } catch (e) {
              alert(e.message || e);
              returnState = false;
          }
      }, "text");
      return returnState;
  };

If I hit print button I immediately getting the “print failed” message - I think this means that if (printnow(data) == true) is not waiting for function printnow(data) to be completed.

How I can return true if printing was success?

if (success == true) {
returnState = true;

aren’t you just…

1. var returnState = false;
2. $.get("./servis.label", function(labelXml) {stuff}, "text");
3. return returnState;

Step 2 is, start the get request.

Step 3 can now proceed, because step 2 was started and now we can go return that variable we have set to false in step 1 already. Why does Javascript have to wait synchronously for the asynchronous $get to finish doing anything?
What if you got rid of steps 1 and 3, and then

$.get("./servis.label", function(labelXml) {
    try {...
          var success = label.print(printerName);
          return ((success==true) ? true : false);
      }
      catch (e) {
          alert (e.message || e);
          return false;
      }
  }, "text");

Now there’s no step after the async part. Or the get could have a “then” or “done” method after it, but be really careful doing that in jQuery, it’s got “promises” but they’re apparently quite different from standard promises.

I’m not sure if Promises would solve the “async call calls another async call” part, but that might be worth exploring if your real code has lots of error catching bits.

AFAIK the difference is how thrown errors are handled. which will be fixed in jQuery 3.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.