http://blog.grossman.io/how-to-write-async-await-without-try-catch-blocks-in-javascript/ In this link, there are some codes that access to a variable in try catch but when I try this in my server It doesn't work because It's out of scope. how can I do this?
try {
const foo = "bar"
} catch (e) {
console.log(e)
}
try {
console.log(foo) -> is not defined
} catch (e) {
console.log(e)
}
Variables in try block So, if you declare a variable in try block, (for that matter in any block) it will be local to that particular block, the life time of the variable expires after the execution of the block. Therefore, you cannot access any variable declared in a block, outside it.
Yes, we can declare a try-catch block within another try-catch block, this is called nested try-catch block.
You cannot have multiple try blocks with a single catch block. Each try block must be followed by catch or finally.
Yes, we can define one try block with multiple catch blocks in Java.
The author of that post clearly did a mistake there––it happens to all of us.
So, the const
declarations are block-scoped, like the docs say:
Constants are block-scoped, much like variables defined using the let statement. The value of a constant cannot change through re-assignment, and it can't be redeclared.
That's why you cannot access it outside of the try-catch block.
To solve the problem:
Either use var
instead of const:
try {
// When declared via `var`, the variable will
// be declared outside of the block
var foo = "bar"
} catch (e) {
console.log(e)
}
try {
console.log(foo)
} catch (e) {
console.log(e)
}
Or you can declare the variable outside of the try-catch
, using let
:
// Maybe it's clearer to declare it with let and
// assign the value in the first try-catch
let foo;
try {
foo = "bar"
} catch (e) {
console.log(e)
}
try {
console.log(foo)
} catch (e) {
console.log(e)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With