What will happen when return new Promise((resolve, reject) => {}) forgot to call either resolve or reject? [duplicate]

强颜欢笑 提交于 2019-12-04 20:25:44

Internally, a promise can be in one of three states:

Pending, when the final value is not available yet. This is the only state that may transition to one of the other two states. Fulfilled, when and if the final value becomes available. A fulfillment value becomes permanently associated with the promise. This may be any value, including undefined. Rejected, if an error prevented the final value from being determined. A rejection reason becomes permanently associated with the promise. This may be any value, including undefined, though it is generally an Error object, like in exception handling.

https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Promise

In your case, the promise is in the pending state and calling demo function will always in wait for the promise status to be fulfilled or rejected.

A promise is always expected to either resolve or reject. If you intend to do a no follow up, you may resolve with an empty dataset or reject with an error code that suits your use case.

You may use Promise.race to check if a promise was finished on time. So if you forgot to call resolve or reject into your promise, then Promise.race still be resolved or rejected after delay.

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