简体   繁体   English

在Node.js中阻止IO

[英]blocking IO in nodejs

I am developing an application using NodeJS where two queries depend on each other here is explanation of my situation. 我正在使用NodeJS开发一个应用程序,其中两个查询相互依赖,这是对我的情况的解释。

I have to query database for some values say A then I have to query database for some other value B only if there is an A in the database. 我必须向数据库查询一些值,比如说A,然后仅当数据库中存在A时,才需要向数据库查询其他值B。

I know I can do this in NodeJS' natural way like execute query for A when its result is ready execute query for B in A's callback and then finally render response in B's callback. 我知道我可以使用NodeJS的自然方法来执行此操作,例如在结果准备好后执行A的查询,然后在A的回调中执行B的查询,然后最终在B的回调中呈现响应。

Here is my question, is there a design issue in the solution I just mentioned perhaps about nested callbacks. 这是我的问题,我刚才提到的解决方案中是否存在关于嵌套回调的设计问题。

Second is there any method in which I can make NodeJs IO as Blocking from NON-Blocking? 其次,有什么方法可以使NodeJs IO成为非阻塞阻塞?

I was made aware of a library called Async Which i wish id found when i started my NodeJs projects. 我意识到一个名为Async的库,希望在启动NodeJs项目时找到ID。 It can take care of this and much more. 它可以解决这个问题以及更多。

Async provides around 20 functions that include the usual 'functional' suspects (map, reduce, filter, each…) as well as some common patterns for asynchronous control flow (parallel, series, waterfall…). 异步提供了大约20个功能,其中包括通常的“功能”可疑对象(映射,缩小,过滤器,每个……)以及异步控制流的一些常见模式(并行,串联,瀑布式……)。 All these functions assume you follow the node.js convention of providing a single callback as the last argument of your async function. 所有这些函数都假定您遵循提供单个回调作为async函数的最后一个参数的node.js约定。

basic example from site that would help in your scenario 该站点的基本示例将对您的情况有所帮助

async.series([
    function(callback){
        // do db call one
        callback(null, 'one');
    },
    function(callback){
        // do db call two
        callback(null, 'two');
    }
],
function(err, results){
    // results is now equal to ['one', 'two']
}); 

Here is my question, is there a design issue in the solution I just mentioned perhaps about nested callbacks. 这是我的问题,我刚才提到的解决方案中是否存在关于嵌套回调的设计问题。

No, your solution is perfectly fine. 不,您的解决方案非常好。

Second is there any method in which I can make NodeJs IO as Blocking from NON-Blocking? 其次,有什么方法可以使NodeJs IO成为非阻塞阻塞?

Yes. 是。 You can write your own c++ extension to provide blocking calls. 您可以编写自己的c ++扩展来提供阻塞调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM