0

I have this situation

try {
  const foo = await Foo();
} catch (error) {
  console.error(error);
  throw error;
}

I have to do a fair amount of stuff with the foo variable.

Is there a way I can use the foo variable without ending up nested several layers deeper because of try/catch blocks like this? This standard pattern won't work because it's const (and I prefer it to be const):

let x;
try {
  x = await X():
} catch (error) {
  throw error;
}
console.log(x);
theonlygusti
  • 11,032
  • 11
  • 64
  • 119
  • Why do you think you would end several layers nested? Can you show in code what do you mean if you would use it in the way that you forsee would cause nesting? – Ma3x Jan 06 '22 at 23:10
  • @Ma3x I just don't want lots of my code an extra layer indented – theonlygusti Jan 06 '22 at 23:11
  • So you want a try/catch expression (instead of a statement), but JS does not have one. See: https://stackoverflow.com/questions/5126560/try-catch-oneliner-available – Ma3x Jan 06 '22 at 23:15
  • 1
    Does https://stackoverflow.com/questions/44663864/correct-try-catch-syntax-using-async-await answer your question? Basically either do the "*fair amount of stuff with the `foo` variable*", inside the `try` block, or use `const foo = await Foo().catch(…);` – Bergi Jan 06 '22 at 23:50
  • Are you catching the "several layers" of promises differently? If not, you could just have one try/catch for all of your await/promise based statements – Matt Davis Jan 06 '22 at 23:50
  • I have one solution, but it a way to use it if want to write this kind of code then you can you can use "Promise" to assign const variable EX:- const data= await new Promice( ()=>{// here yo can handle error or data } ) ------if you want complete example let me Know – bhavesh Jan 07 '22 at 06:39
  • @Bergi `const foo = await Foo().catch(…);` looks like a great solution – theonlygusti Jan 07 '22 at 08:37

0 Answers0