'NodeJS stop main function when nested callback throws an exception

I'm quite new to NodeJS, and I came across a construction that I can't wrap my head around. Consider the following code:

router.get("/", function(req, res, next) {
    let db = new sqlite3.Database(dbname, sqlite3.OPEN_READONLY, (err) => {
        if (err) next(err);
    });

    res.render("views/page");
}

If an exception is raised by Database (for instance because dbname does not exist), then the callback will pass it to the Express error handler (next). But the code does not stop there, and it will continue to execute the next line and attempt to render something, which is problematic if the error handler also sends headers. If I add a return statement within the callback, it will simply terminate Database but not the rest of the function.

My question: is there anyway to prevent the rest of the code from being executed if an exception is raised?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source