As mentioned in this answer;
Most code that uses promises expects them to resolve or reject at some
point in the future (that's why promises are used in the first place).
If they don't, then that code generally never gets to finish its work.
It's possible that you could have some other code that finishes the
work for that task and the promise is just abandoned without ever
doing its thing. There's no internal problem in Javascript if you do
it that way, but it is not how promises were designed to work and is
generally not how the consumer of promises expect them to work.
Failing to resolve or reject a promise doesn't cause a problem in Javascript, but it's a bad practice anyway. Your application cannot determine what happened to the promise if it never resolves. Instead of leaving the promise in limbo, return a value like an error message, and have the promise filter results for an error message. If it finds an error, reject() the promise so the application can determine its next move.
var listen = document.querySelector("#listen"),
cancel = document.querySelector("#cancel"),
submit = document.querySelector("#submit");
var promiseResolve = null;
listen.addEventListener("click", startListening);
cancel.addEventListener("click", onCancelClick);
submit.addEventListener("click", onSubmitClick);
submit.disabled = true;
function startListening() {
submit.disabled = false;
listen.disabled = true;
new Promise(function(resolve, reject) {
promiseResolve = (error) => {
if (error) { reject(error); } else { resolve(); }
};
}).then(onSubmit)
.catch(error => onError(error));
}
function abort() {
listen.disabled = false;
submit.disabled = true;
promiseResolve = null;
}
function onSubmitClick() {
if (promiseResolve) promiseResolve();
}
function onCancelClick() {
if (promiseResolve) promiseResolve("Cancelled!");
}
function onSubmit() {
console.log("Done");
abort();
}
function onError(error) {
console.warn(error);
abort();
}
<button id="listen">Listen</button>
<button id="submit">Submit</button>
<button id="cancel">Cancel</button>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…