[英]Using Promise.reject() in async/await catch handler
I just wanted to know if it's a good practice to use the following code:我只是想知道使用以下代码是否是一个好习惯:
const myFun = async () => {
try {
const response = await api();
if(response.status === 200) {
return response.data;
}
} catch(err) {
return Promise.reject(err);
}
}
Here myFun
will return a resolved/reject Promise that will be caught by another function. I just wanted to know if this is right way or are there any alternatives?这里
myFun
将返回一个已解决/拒绝的 Promise,它将被另一个 function 捕获。我只是想知道这是正确的方法还是有其他选择?
You are achieving nothing by trying to re-throw the error from api()
.尝试从
api()
重新抛出错误将一事无成。
Using async
function will cause Promise.reject(error)
to be called implicitly when an error is thrown anyway.使用
async
function 将导致Promise.reject(error)
在抛出错误时隐式调用。
Just write your function like this:像这样写你的 function:
const myFun = async () => {
const response = await api();
if (response.status === 200) {
return response.data;
}
// You might want to return something else here
}
Then the calling function will still receive the error:那么调用function还是会报错:
try {
await myFun();
} catch (error) {
// error still received
}
What you are doing is mixing async/await and Promises.你正在做的是混合 async/await 和 Promises。 You can just
throw
the err
from inside the catch block.您可以从 catch 块中
throw
err
。
const myFun = async () => {
try {
const response = await api();
if(response.status === 200) {
return response.data;
}
} catch(err) {
throw err;
}
}
After this you can catch the error wherever you call myFun
.在此之后,您可以在任何调用
myFun
的地方捕获错误。
The end result in both cases would be the same.两种情况的最终结果都是一样的。 The only difference is that
throw
can be used anywhere in JS code but Promise.reject
can only be called from within an asynchronous code block only唯一的区别是
throw
可以在 JS 代码的任何地方使用,但是Promise.reject
只能在异步代码块中调用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.