如何检查Promise是否有待处理

编程入门 行业动态 更新时间:2024-10-25 06:28:30
本文介绍了如何检查Promise是否有待处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有这种情况,我想知道承诺的状态。下面,函数 start 只调用 someTest ,如果它不再运行(Promise未挂起)。可以多次调用 start 函数,但如果在测试仍在运行时调用它,它将不会等待并返回 false

I have this situation in which I would like to know what the status is of a promise. Below, the function start only calls someTest if it is not running anymore (Promise is not pending). The start function can be called many times, but if its called while the tests are still running, its not going to wait and returns just false

class RunTest { start() { retVal = false; if (!this.promise) { this.promise = this.someTest(); retVal = true; } if ( /* if promise is resolved/rejected or not pending */ ) { this.promise = this.someTest(); retVal = true; } return retVal; } someTest() { return new Promise((resolve, reject) => { // some tests go inhere }); } }

我找不到简单检查状态的方法一个承诺。像 this.promise.isPending 之类的东西会很好:)任何帮助都会受到赞赏!

I cannot find a way to simply check the status of a promise. Something like this.promise.isPending would be nice :) Any help would be appreciated!

推荐答案

您可以附加一个然后处理程序,在promise(或<)上设置 done 标志code> RunTest 实例(如果您愿意),并测试:

You can attach a then handler that sets a done flag on the promise (or the RunTest instance if you prefer), and test that:

if (!this.promise) { this.promise = this.someTest(); this.promise.catch(() => {}).then(() => { this.promise.done = true; }); retVal = true; } if ( this.promise.done ) { this.promise = this.someTest(); this.promise.catch(() => {}).then(() => { this.promise.done = true; }); retVal = true; }

注意空 catch() handler,无论promise的结果如何,都要调用处理程序是至关重要的。 您可能希望将其包装在函数中以保持代码DRY。

Notice the empty catch() handler, it's crucial in order to have the handler called regardless of the outcome of the promise. You probably want to wrap that in a function though to keep the code DRY.

更多推荐

如何检查Promise是否有待处理

本文发布于:2023-11-09 20:23:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1573342.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Promise

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!