1

我正在使用打印工具,我尝试按如下方式查找打印机

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
               
}

因此,当上述运行并找到打印机时 this.Printers 的值为。哪个是对的

this.Printers = "Found a printer"

但是当我找不到打印机时 this.Printers 看起来像

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

所以在我的捕获i tried中分配this.Printers=null为一个测试,看看它是否会返回,但我仍然没有得到

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

当 this.Printers无法使用 [[PromiseResult]]: undefined 或 null 时,如何分配它?

4

1 回答 1

0

引用@ivar

您似乎误解了 Promises 和异步流程的工作方式

我同意这个说法,但更进一步,你做了一些非常奇怪的事情,你在它自己的函数中重新定义了一个变量。

在某些语言中,例如 Visual Basic,使用函数赋值作为返回变量是很正常的,但在 JavaScript 中这是不正常的。

此外,promise 中的return关键字将值传递给下一个 promise,它不会退出函数!

您的代码应如下所示:

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);
});

...但是这可能是不可取的,特别是如果您希望使此函数调用同步。要使其同步,请尝试以下操作:

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);

如果您不确定是否使用asyncand await,请参阅以下问题:How and when to use 'async' and 'await'</a>

这是使用 qz-tray 和 promises 的分步教程:https ://www.youtube.com/watch?v=wKIY4gqkIFE

警告,asyncandawait关键字与 Internet Explorer 不兼容。

于 2021-05-11T15:12:36.983 回答