Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

async方法最好是用try,catch的写法来写 #34

Open
yuandaishi opened this issue Mar 7, 2020 · 0 comments
Open

async方法最好是用try,catch的写法来写 #34

yuandaishi opened this issue Mar 7, 2020 · 0 comments
Labels
javascript something about javascript

Comments

@yuandaishi
Copy link
Owner

如下代码:

getMessage = () => {
    return new Promise((resolve,reject) => {
        setTimeout(() => {
            //resolve('1');
            reject(new Error('error'));
        }, 300);    
    })
}

result = async() => {
    let res = await getMessage();
    console.log(`res:${res}`);
}

这个时候,我们执行result函数,会报错,因为promise走了catch流程,所以我们的result函数最好用try,catch包裹起来,如下代码:

result = async() => {
    try {
        let res = await getMessage();
        console.log(`res:${res}`);
    } catch (error) {
        console.log(error)
    }
}
@yuandaishi yuandaishi added the javascript something about javascript label Mar 7, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
javascript something about javascript
Projects
None yet
Development

No branches or pull requests

1 participant