如果执行者未解决ES6 JavaScript承诺,可以通过其他任何方式解决吗? [英] Can an ES6 JavaScript promise be resolved by anything else if it is not resolved by the executor?

查看:32
本文介绍了如果执行者未解决ES6 JavaScript承诺,可以通过其他任何方式解决吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果以这种方式创建承诺:

If a promise is created this way:

myPromise = new Promise(function(resolve, reject) {});

这个诺言可以通过任何方式解决吗?显然,在这种情况下,执行者无法解决问题,那么诺言能否得到解决?

Can this promise be ever resolved by any way? Obviously, the executor is not resolving it in this case, so can the promise be ever resolved?

我认为如果它是jQuery,则可以通过 deferred.resolve()进行解析,以便解决相关的诺言 deferred.promise().

I think if it is jQuery, it can be resolved by deferred.resolve() so that the related promise deferred.promise() is resolved.

推荐答案

否,只能分别通过 resolve reject 函数来解决诺言.

No, the promise can only be resolved or rejected by the resolve and reject functions, respectively.

如果这些函数没有被调用或公开,则承诺将永远保持待处理状态.

If these functions aren't called nor exposed, the promise will remain in pending state forever.

这也是一个安全级别,因为它可以帮助您确保等待的诺言能够解析为您期望的值以及您期望的值;并允许您安全地返回内部承诺(没有任何危险或泄露秘密).

That's also a security level, as it helps you ensure the promise you wait for will resolve to the value you expect and when you expect; and allows you to safely return an internal promise, as it is (without any hazards or leaking secrets).

要做出承诺,它依赖于您没有控制权的另一个承诺,但是可以手动解决(或拒绝),而不论原始承诺如何,都可以使用 Promise.race()功能:

To make a promise, that relies on another promise you don't have control over, but can be resolved (or rejected) manually, regardless of the original, you can use the Promise.race() function:

//The original promise that may pend forever
const original = new Promise(()=>{})

//Controller promise, whose resolver is exposed (or contains the logic needed for "manual" resolution)
let resolve
const controller = new Promise(rs=>{resolve=rs})

//The promise you wait for (and can be resolved or rejected either by `original` or `controller`)
const mixed = Promise.race([original,controller])

mixed.then(console.log)

setTimeout(()=>resolve('Resolved'), 2000)

这篇关于如果执行者未解决ES6 JavaScript承诺,可以通过其他任何方式解决吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆