简体   繁体   中英

Error handling in the Promise constructor

What is the best practice for error handling in the Promise constructor?

Promises has the great advantage of propagating error in the promise chain, and errors can not escape, but when it comes to the Promise constructor, you have to manually handle the possible errors.

Let me show an example:

new Promise(resolve => {
    throw new Error('error in the constructor');
    resolve();
});

When the above code runs, the promise never gets resolved (or rejected), so I'm not able to handle the Error up in the promise chain. Now one obvious solution would be:

new Promise((resolve, reject) => {
    try {
        throw new Error('error in the constructor');
        resolve();
    } catch(error) {
        reject(error)
    }
});

But it seems to be a little bit overkill for me to do this manual error checking all the time in the constructor, meanwhile for example in the Promise's then method I do not need this.

So for example the following solution does the same, but without the manual error handling:

Promise.resolve()
    .then(() => {
        throw new Error('error in the constructor');
    });

So my question is, that is there a better way to do the error handling in the Promise constructor? Or should I use the last example, which is in my opinion much cleaner.

when it comes to the Promise constructor, you have to manually handle the possible errors.
[…]
When the above code runs, the promise never gets resolved (or rejected)

You misobserved that. In any ES6-compliant Promise implementation, the promise will get rejected when you throw an exception (synchronously) from the new Promise constructor's resolver callback. This throw -safety was one of the compelling arguments to favor the Promise constructor over the deferred pattern .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM