2 ms·
Consider the case where you want to iterate over an input file, query data from a database with those inputs, and write the outputs as lines to an output file.
by bastawhiz 3y ago
Consider the case where you want to iterate over an input file, query data from a database with those inputs, and write the outputs as lines to an output file. The function can fail anywhere: between opening the input file, connecting to the database, or opening the output file. With try/finally, you need to keep the variables outside the scope of your try block and check whether each one has been set in the finally (and clean them up). I.e., if the database connection fails, you don't want to try closing the output file because you haven't opened it yet. The resulting code is sloppy.
The "best" way to do this in JS today is to have one function that opens and cleans up the input file (with a try/finally). That function calls another that opens and cleans up the db connection in the same way, and so on. That's verbose and makes your code nonlinear.
The new keyword brings Go's (and other languages') equivalent of 'defer' to JS. You don't need to worry about cleaning up, the 'using' keyword implies that it happens for you.