0

I am using qz print Api for printing labels.It has its own function (JS) which displays default printer in alert. I want to display printer name in a div. I have achieved till now. My code is below.

function useDefaultPrinter() {
var printer; 
if (isLoaded()) {
// Searches for default printer
qz.findPrinter();
window['qzDoneFinding'] = function() {
// Alert the printer name to user
printer = qz.getPrinter();

window['qzDoneFinding'] = null;
defaultFound = true;
};
    }
alert(printer);
return(printer);
}

For displaying HTML

var printer_name = useDefaultPrinter();
lbDownHtml += "<div><span>Default printer found: '" + printer_name + "'</span>";
lbDownHtml += "</div>";

The problem is that if i dont use alert(printer) in useDefaultPrinter() before return it displays undefined, but if the alert is there like above code it displays undefine in alert but perfect output in html where i have print it. What is the issue? as i dont want to alert (but if i dont use it it shows undefined).

Ammar Ul Hassan
  • 826
  • 1
  • 18
  • 48

1 Answers1

1

I know very little about this API, but this is actually a common issue.

The qz.findPrinter() function appears to be asynchronous - it will still be actively running when your useDefaultPrinter function has finished.

For asynchronous functions, you cannot simply return the value you want, because it doesn't exist yet. The most common resolution is to add a "callback" argument to your function (callback would, itself, be a "function variable"). Then, call that callback function when the object you need is available. In your code, this would be here:

// Alert the printer name to user
printer = qz.getPrinter();

Once that's in place, you would need to rewrite whatever code outside needs useDefaultPrinter.

Before:

printer = useDefaultPrinter();
// continue operation here...

After:

useDefaultPrinter(function(printer) {
  //...continue operation here...
});

If you're still confused, search Google for "tutorials on JavaScript asynchronous programming". Based on your username, it seems possible that English is not your first language, so it might be easier to follow if you can find a description that fits your learning style - it tends not to make sense at first for most developers.

Katana314
  • 8,429
  • 2
  • 28
  • 36