Is the try-catch-finally block synchronous in node.js?
Asked Answered
Q

2

11

I have some code runing in a child process in a node program like so:

try{
    var data = fs.readFileSync(urlPath, {"encoding":"utf8"});
} catch (err) {
    console.log("Error reading url file...");
    throw err;
} finally {
    console.log("File read!");
    var array = data.split("\n");

    console.log("Found " + array.length + " urls");

This code is called from another node program, that needs to wait until all the operations in this file are done. Unfortunately, the child process is exiting with code 0 before any of the code under the finally block is executed.

This is leading me to believe even the try-catch-finally is asynchronous. Is that correct?

Quotient answered 10/7, 2013 at 13:44 Comment(3)
That really wouldn't make sense.Mestas
Maybe I should open a new question, I just added some logging statements elsewhere and it appears the child process is exiting without even running those.Quotient
@MattBall please refer to this question: #17573334Quotient
C
19

Your question is confusingly worded.

The entire Javascript language is fully synchronous; all language constructs, including catch and finally blocks, will execute synchronously before running the next line of code.

However, they are not aware of any asynchronous operations that may have begun, and will not wait for them to finish.

Catsup answered 10/7, 2013 at 13:47 Comment(1)
Please refer to this question: #17573334Quotient
H
1

There are some ways to overcome this:

1) https://github.com/CrabDude/trycatch

See also http://nodejs.org/api/domain.html

Habilitate answered 13/8, 2014 at 15:15 Comment(1)
domain is deprecared!Sim

© 2022 - 2024 — McMap. All rights reserved.