Promises are often used in daily development. But have you noticed anything about exception catching for promises?

wedge

function foo() {
    return new Promise((res, rej) = > {
        rej(`error`)})}try {
    foo();
}
catch (e) {
    console.log(e, 'An error has occurred! `);
}
Copy the code

The result of executing this code is obviously an error. Let’s look at the different error messages in the browser and node.



The exception will be thrown into the global as’ Uncaught(in promise) ‘.

On (‘unhandledRejection’,e=>{… }) to catch global errors.

But in the browser, there is no efficient way to catch such global exceptions.

So we should try to keep promise errors from being thrown into the global environment.

Use catch method

function foo() {
    return new Promise((res, rej) = > {
        rej(`error`)
    })
}

foo().catch(e= > {
    console.log(e, 'An error has occurred! `);
})
Copy the code

Use async/await and try/catch

function foo() {
    return new Promise((res, rej) = > {
        rej(`error`)})}async function test() {
    try {
        await foo()
    }
    catch (e) {
        console.log(e, 'An error has occurred! `);
    }
}

test()
Copy the code


Exceptions about promises must be caught in either of these ways


Record the record!