Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Variable outside of callback in NodeJS

Variable outside of callback in NodeJS

Problem

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, fields) {

        if (err) {
          throw err;
        }

        console.log(results);
        console.log(fields);

        data.push(results);
      }
    );

    console.log(data);

How can I get access to the results (or data) var outside of the callback? I don't want to have to write a ton of callbacks inside of each other when running queries.

Problem courtesy of: mikelbring

Solution

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 courtesy of: jimbojw

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Variable outside of callback in NodeJS

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×