问题是这样的function demo() { return new Promise((resolve, reject) => { ... // The problem here!! //I just found in some rare case we failed to call resolve or reject })}demo() .then(res => { console.log('resolve') console.log(res) }) .catch(rej => { console.log('reject') console.log(rej) }) .finally(() => { console.log('why') })当我无法调用“解决”或“拒绝”时,甚至都不会调用“ finally”块!为什么 ?我以为这是一个错误,然后我发现原始作者似乎是故意这样做的,如果他既不调用解决方案也不拒绝,则不应调用then / catch / finally,即在这种情况下不采取后续行动应采取。但这是处理不应该采取后续行动的情况的有效方法吗?会带来什么麻烦吗?- - - 更新 - - -即使我的问题被标记为重复,我仍然对我得到的答案不满意。最初,我认为让诺言永远保持待定状态是一个坏主意。但是,SO的回答是“不应有副作用”。永远不会解决的承诺会导致内存泄漏吗?还说:“总之,至少在现代浏览器中,只要您没有外部引用它们,就不必担心未解决的承诺”。因此,如果这样做的话,让promise保持待定状态似乎是可以的。
3 回答

慕仙森
TA贡献1827条经验 获得超8个赞
您可以Promise.race用来检查诺言是否按时完成。因此,如果您忘记打电话resolve或reject兑现诺言,那么Promise.race延误后仍然会得到解决或拒绝。
var promise1 = new Promise(function(resolve, reject) {
setTimeout(reject, 500);
});
var promise2 = new Promise(function(resolve, reject) {
});
Promise.race([promise1, promise2]).then(function(value) {
console.log(value);
}).catch(err => console.log('promise rejected'));
添加回答
举报
0/150
提交
取消