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

异步编程模型中的异常处理链条 #5

Open
lovelmh13 opened this issue Jul 21, 2019 · 0 comments
Open

异步编程模型中的异常处理链条 #5

lovelmh13 opened this issue Jul 21, 2019 · 0 comments

Comments

@lovelmh13
Copy link
Owner

try catch可能捕捉不到异步的异常

function fn1 () {
	try {
		fn2();
    } catch (err) {
		console.log(err);	// 不会打印
    }
}

function fn2 () {
    setTimeout(function () {
		throw new Error('error');	// 只会抛出错误
    }, 1000);
}

无脑方法

当遇到返回的是promise(async 标识的函数就是返回promise),就无脑加async await。这样就可以try catch来捕捉异常。

那么下面这个可以被捕捉到吗?

async function fn3 () {
   try {
   	await fn4();
   } catch (err) {
   	console.log(err);	// 不会打印
   }
}

async function fn4 () {
   await setTimeout(function () {
   	throw new Error('error');	// 只会抛出错误
   }, 1000);
}

不可以! await要加在异步的函数上面,返回回来才有意义。也就是setTimeout的回调函数。

需要这样使用:

async function fn5 () {
    try {
        await fn6();
    } catch (err) {
        console.log(err);	// 打印 error async
    }
}

function fn6 () {
    return new Promise((resolve, reject) => {
        setTimeout(function () {
            const r = Math.random();
            if (r < 0.9) {
                reject('error async');
            }
        });
    });
}

正常情况,只有throw一个异常,才能被try catch到。但是await 具备promise里面reject出来的异常。可以理解成await又把rejectthrow了,所以被catch到了。

参考:纯正商业级应用-Node.js Koa2开发微信小程序服务端

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant