首页 > 解决方案 > 你如何在 Javascript 中逃避 try/catch 地狱?

问题描述

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

但是我该怎么办。

我想这样做..

let a = await doAbc();
let b = await do123(a);

相反,它变成了

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

在这一点上,我对一切感到后悔。

标签: javascripterror-handling

解决方案


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

let a = await doAbc().catch(doZxc); // or .catch(() => doZxc())
let b = await do123(a);

甚至

 let b = await doAbc().catch(doZxc).then(do123);

连同您的其余代码:

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

推荐阅读