admin管理员组文章数量:1356423
Ok, I like(d) try/catch with await/async.
But what do I do with this.
I wanted to do this..
let a = await doAbc();
let b = await do123(a);
what it bees instead is
let a, b;
try {
a = await doAbc();
} catch(e) {
a = await doZxc();
}
try {
b = await do123(a);
} catch (e) {
console.log(e);
return;
}
if (b.data == undefined) {
return -1;
} else {
return b;
}
At this point I'm regretting everything.
Ok, I like(d) try/catch with await/async.
But what do I do with this.
I wanted to do this..
let a = await doAbc();
let b = await do123(a);
what it bees instead is
let a, b;
try {
a = await doAbc();
} catch(e) {
a = await doZxc();
}
try {
b = await do123(a);
} catch (e) {
console.log(e);
return;
}
if (b.data == undefined) {
return -1;
} else {
return b;
}
At this point I'm regretting everything.
Share Improve this question edited Oct 26, 2018 at 2:19 Muhammad Umer asked Oct 26, 2018 at 2:12 Muhammad UmerMuhammad Umer 18.2k24 gold badges110 silver badges176 bronze badges 7- why have you stopped using await? – Bravo Commented Oct 26, 2018 at 2:14
- You make use of Promises. – Obsidian Age Commented Oct 26, 2018 at 2:14
- I'm using await, async and thus promises, i didn't write them for sake of pesudo code – Muhammad Umer Commented Oct 26, 2018 at 2:19
-
do you think
doAbc .catch(doZxc) .then(d123) .then(b => b.data === undefined ? -1 : b, e => { console.log(e); return; });
is easier to read? – Bravo Commented Oct 26, 2018 at 2:20 - 1 @MuhammadUmer - always use the right tool for the job :p – Bravo Commented Oct 26, 2018 at 2:24
3 Answers
Reset to default 6Remember that you can await
any promise. So you could do:
let a = await doAbc().catch(doZxc); // or .catch(() => doZxc())
let b = await do123(a);
Or even
let b = await doAbc().catch(doZxc).then(do123);
Together with the rest of your code:
try {
let b = await doAbc().catch(doZxc).then(do123);
return b.data == undefined ? -1 : b;
} catch (e) {
console.log(e);
return;
}
If it's all in one logical function, you can group all your await
in one try and then take action based on error.
let a
let b
try {
a = await doAbc();
b = await do123(a);
} catch (err) {
// take appropriate action based on err
}
Create to function first return a and second using first function returned value to create b , somthing like this code
function firstCode(){
try {
a = await doAbc();
} catch(e) {
a = await doZxc();
}
return a;
}
function secondFunction(){
try {
b = await do123(firstFunction());
} catch (e) {
console.log(e);
return;
}
}
本文标签: error handlingHow do you escape trycatch hell in JavascriptStack Overflow
版权声明:本文标题:error handling - How do you escape trycatch hell in Javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744055754a2583219.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论