Try/catch块打破异步JS代码

Pat*_*ors 0 javascript node.js async-await

我有以下数据库调用

const x = await doThis();
cons y = await doThat(x);

return somethingElse(x,y)
Run Code Online (Sandbox Code Playgroud)

这样可以正常工作,但是如果未正确返回promise,则无法进行调试.我想编写类似下面的代码

  try {
    const x = await doThis();
  } catch (e) {
    console.log(e);
  }
  try {
    cons y = await doThat(x);
  } catch (e) {
    console.log(e);
  }
  return somethingElse(x,y);
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下错误:

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: x is not defined
Run Code Online (Sandbox Code Playgroud)

try/catch块是否会停止代码异步运行?我该如何解决?

Sur*_*yan 6

使用letconst使用括号范围声明变量时.

在你的代码的一部分x,并y支架作用域他们的try发言-那么,为什么他们没有的外部定义try.您需要在try语句之前定义它们.

你也可以constvar.这将在函数的开头提升变量声明(基于return它是一个函数的语句)并且将起作用 - x并且y对整个函数可见,但我建议使用带let声明的方法.

let x, y;

try {
   x = await doThis();
} catch (e) {
   console.log(e);
}

try {
   y = await doThat(x);
} catch (e) {
   console.log(e);
}

return somethingElse(x,y);
Run Code Online (Sandbox Code Playgroud)