NodeJS中回调之外的变量 [英] Variable outside of callback in NodeJS

查看:149
本文介绍了NodeJS中回调之外的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对NodeJS和JavaScript一般都很新。这是我的脚本:

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

如何访问结果 (或 data )var外面的回调?

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.

推荐答案

你在做什么?我不想在运行查询时在对方之间写入大量的回调。请求是同步(或阻塞)执行,这真的违背了node.js的设计和精神。

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

Node,像JavaScript,是单线程的。如果您有阻止代码,则整个过程停止

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.

因此,这是可能的可以给你一个如何使这个阻塞,同步调用的答案。如果是这样,如果你实现它,你做错了。您也可以使用多线程脚本语言,如Ruby或Python。

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.

这篇关于NodeJS中回调之外的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆