try catch promise.reject

突发奇想,测试了下面的一段代码,

function f() {
    try{
        Promise.reject('我错了');
    }catch(e){
        console.log('e',e);
    }
}
f();

结果没有catch,我就不明白了,到底为什么。

因为Promise.reject是异步?

我问别人,有人告诉我是因为异步,但是我认为不是这个原因,因为promise.reject会直接返回一个rejected的promise

The Promise.reject(reason) method returns a Promise object that is rejected with the given reason.

然后我就搜啊搜。。。

####什么时候进入catch

the catch block is entered when any exception is thrown.
在try里面有throw (或者隐式的throw),才会进入catch 。
那么好办了:

 function f() {
    try{
        throw Promise.reject('我错了');
    }catch(e){
        console.log('e',e);
    }
}
f();

进入catch了,输出如下:

e Promise {  '我错了' }

####加上async await呢?

async function f() {
    try{
        await Promise.reject('我错了');
    }catch(e){
        console.log('e',e);
    }
}
f(); 
e 我错了

为什么这个就进入catch了呢,

If the Promise is rejected, the await expression throws the rejected value.

换句话说, await Promise.reject(‘我错了’); 相当于 throw ‘我错了’;
当后面的promise 被reject之后,await会进行一个throw的操作。
比如JSON.parse出错的时候也会进行throw,

async function f() {
    try{
        // await Promise.reject('我错了');
        // throw '我错了';
        JSON.parse('fsafsd');
    }catch(e){
        console.log('e',e);
    }
}
f();
e SyntaxError: Unexpected token s in JSON at position 1

Throws a SyntaxError exception if the string to parse is not valid JSON.

你可能感兴趣的:(try catch promise.reject)