How to set a promise value that has failed

224 Views Asked by At

I am using a printing tool in which i try to find the printers as follows

this.Printers = qz.websocket.connect().then(() => {
               return qzTray.printers.find("found a printer");
            }).then((found) => {
                this.Printers = found;
                return this.Printers;
            }).catch((e) => {
                console.log('failed printing');
                 this.Printers=null;
                 return this.printers
               
}

so when the above runs and it finds a printer this.Printers has a value as. which is correct

this.Printers = "Found a printer"

But when i cant find a printer this.Printers looks like

Promise {<pending>}__proto__: Promise[[PromiseState]]: "pending"[[PromiseResult]]: undefined

so in my catch i tried to assign this.Printers=null as a test to see if it returns that out but it doesnt i still get

Promise {<pending>}__proto__: Promise[[PromiseState]]: "pending"[[PromiseResult]]: undefined

how can i assign this.Printers when it fails to use [[PromiseResult]]: undefined or null?

1

There are 1 best solutions below

0
On

Quoting @ivar

You seem to be misunderstanding how Promises and the asynchronous flow work

I agree with this statement, but to take it a bit further, you're doing something very odd, you're redefining a variable inside it's own function.

In some languages, such as Visual Basic, it's normal to use function assignment as a return variable, but this is not normal in JavaScript.

Furthemore, the return keyword in a promise passes the value to the next promise, it does NOT exit a function!

Your code should instead look like this:

var Printers;

qz.websocket.connect().then(() => {
   return qz.printers.find();
}).then((found) => {
   Printers = found;
}).catch((e) => {
   console.log('failed to connect or to find printers');
   Printers=null;       
}).then(() => {
   console.log(Printers);
});

... however this may not be desirable, especially if you're looking to make this function call synchronous. To make it synchronous, try this instead:

async function getPrinters() {
   if(!qz.websocket.isActive()) {
      await qz.websocket.connect();
   }
   return await qz.printers.find();
}

var Printers;
try {
  Printers = await getPrinters();
} catch {
  Printers = null;
}
console.log(Printers);

If you're unsure whether or not to use async and await, see this question: How and when to use ‘async’ and ‘await’

Here's a step-by-step tutorial for using qz-tray and promises: https://www.youtube.com/watch?v=wKIY4gqkIFE

Warning, the async and await keywords are not compatible with Internet Explorer.