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;
}
}