Skip to content Skip to sidebar Skip to footer

Variable Outside Of Callback In NodeJS

I am fairly new to NodeJS and to JavaScript in general. Here is my script: var data = []; client.query( 'SELECT * FROM cds', function selectCb(err, results, field

Solution 1:

What you're asking for is synchronous (or blocking) execution, and that's really contrary to the design and spirit of node.js.

Node, like JavaScript, is single-threaded. If you have blocking code, then the whole process is stopped.

This means you have to use callbacks for anything that will take a long time (like querying from a database). If you're writing a command-line tool that runs through in one pass, you may be willing to live with the blocking. But if you're writing any kind of responsive application (like a web site), then blocking is murder.

So it's possible that someone could give you an answer on how to make this a blocking, synchronous call. If so, and if you implement it, you're doing it wrong. You may as well use a multi-threaded scripting language like Ruby or Python.

Writing callbacks isn't so bad, but it requires some thought about architecture and packaging in ways that are probably unfamiliar for people unaccustomed to the style.


Solution 2:

Node.js uses the Continuation Passing Style for all of it's asynchronous interfaces. There is a lot of discussion around this and modules that have been created for easing the pain of nested callbacks. There were rumors for awhile that node.js might start reintroducing Promises into it's core in the v0.7.x branch, but I'm not sure if that's true or not.

Short of using one of the flow-control libraries from the link above (or rolling your own), you're either going to have to live with the nested callbacks, or simply provide a function reference for the callback. E.g.,

var data = [],
    handler = function(err, results, fields) {
        if (err) {
          throw err;
        }
        ...
    };
client.query('SELECT * FROM cds', handler);

Post a Comment for "Variable Outside Of Callback In NodeJS"