微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何设置失败的承诺值

如何解决如何设置失败的承诺值

我正在使用一个打印工具,我尝试在其中查找打印机,如下所示

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"

但是当我找不到打印机时,这台打印机看起来像

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

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

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

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

解决方法

引用@ivar

您似乎误解了 Promise 和异步流程的工作原理

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

在某些语言中,例如 Visual Basic,it's normal to use function assignment as a return variable,但这在 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);

如果您不确定是否使用 asyncawait,请参阅此问题:How and when to use ‘async’ and ‘await’

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。