8

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 becomes 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.

7
  • why have you stopped using await?
    – Bravo
    Commented Oct 26, 2018 at 2:14
  • You make use of Promises. 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 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 3

6

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

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
}
2
  • So I'm Using this in context of expressjs. Is there a good pattern to do error handling and all cases at the very top levels. Some errors are such where you want to try different things, and some errors are such that need to tell users sorry not possible or something is wrong. Commented Oct 26, 2018 at 2:23
  • 3
    except an error in doAbc should result in a = await doZxc(); - so close, yet so far from original code
    – Bravo
    Commented Oct 26, 2018 at 2:23
0

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.