Can an ES6 JavaScript promise be resolved by anything else if it is not resolved by the executor?

岁酱吖の 提交于 2021-02-07 11:13:58

问题


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?

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


回答1:


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

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)



回答2:


Assign the resolve function to a variable outside the scope of the promise




回答3:


Above solutions are nice, but I think we can create separate function / class / whatever to make it more hermetic

function CreatePromise (executor) {
    let resolve;
    let reject;

    const promise = new Promise((res, rej) => {
        resolve = res;
        reject = rej;
        executor(res, rej)
    })

    return {
        resolve,
        reject,
        promise
    }
}

const { reject, promise } = CreatePromise((resolve) => {
    setTimeout(() => {
        resolve()
    }, 100000)
})


来源:https://stackoverflow.com/questions/59559897/can-an-es6-javascript-promise-be-resolved-by-anything-else-if-it-is-not-resolved

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!