Variable outside of callback in NodeJS

徘徊边缘 提交于 2019-12-24 10:36:45

问题


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.


回答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.




回答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);


来源:https://stackoverflow.com/questions/7449810/variable-outside-of-callback-in-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!