你如何在 Javascript 中逃离 try/catch 地狱?

Muh*_*mer 7 javascript error-handling

好的,我喜欢(d)尝试/捕获等待/异步。

但是我该怎么办。

我想做这个..

let a = await doAbc();
let b = await do123(a);
Run Code Online (Sandbox Code Playgroud)

它变成了

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;
}
Run Code Online (Sandbox Code Playgroud)

在这一点上,我后悔一切。

Fel*_*ing 6

请记住,您可以做出await任何承诺。所以你可以这样做:

let a = await doAbc().catch(doZxc); // or .catch(() => doZxc())
let b = await do123(a);
Run Code Online (Sandbox Code Playgroud)

甚至

 let b = await doAbc().catch(doZxc).then(do123);
Run Code Online (Sandbox Code Playgroud)

与其余代码一起:

try { 
  let b = await doAbc().catch(doZxc).then(do123);
  return b.data == undefined ? -1 : b;
} catch (e) {
   console.log(e);
   return;
}
Run Code Online (Sandbox Code Playgroud)