admin管理员组文章数量:1394990
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?
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?
-
1
For a function marked as async the correct way is to
throw
– slebetman Commented Jun 11, 2020 at 22:21 -
What do you want to happen when the promise resolves, but status code is not 200? You are resolving with
undefined
when that happens now which is probably not what you want. – jfriend00 Commented Jun 11, 2020 at 23:47
2 Answers
Reset to default 4You are achieving nothing by trying to re-throw the error from api()
.
Using async
function will cause Promise.reject(error)
to be called implicitly when an error is thrown anyway.
Just write your function like this:
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:
try {
await myFun();
} catch (error) {
// error still received
}
What you are doing is mixing async/await and Promises. You can just throw
the err
from inside the catch block.
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
.
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
本文标签: javascriptUsing Promisereject() in asyncawait catch handlerStack Overflow
版权声明:本文标题:javascript - Using Promise.reject() in asyncawait catch handler - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744110374a2591260.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论