简体   繁体   English

Node.js通过if和async调用控制流程

[英]Node.js control flow with if and async call

I am porting rails code to node.js and stuck with a control flow problem. 我正在将rails代码移植到node.js并遇到控制流问题。 What should be the best way to port below code: 移植以下代码的最佳方法是什么:

filter = {blah:blah};

result = {};

if(filters.something) {
   asyncDBCall(function(){
       result.something = somevalue;
   });
}

if(filters.someOtherThing) {
   asyncDBCall(function() {
       result.someOtherThing = someothervalue;
   });
}

return result;

The major advantage and disadvantage of node JS is it's asynchronous nature while executing functions. 节点JS的主要优缺点是执行功能时具有异步特性。 Your code should be 您的代码应为

if (filters.something) {
    asyncDBCall(function() {
        result.something = somevalue;
        return result;
    });
}

if (filters.someOtherThing) {
    asyncDBCall(function() {
        result.someOtherThing = somevalue;
        return result;
    });
}

However if it is possible that both the conditions are true. 但是,如果这两个条件都可能成立,则是可能的。 In that case you have to wait for the other asyncDBCall to finish before making the next asyncDBCall. 在这种情况下,您必须等待另一个asyncDBCall完成之后再进行下一个asyncDBCall。 The code would be 该代码将是

if (filters.something) {
    asyncDBCall(function() {
        result.something = somevalue;
        if (filters.someOtherThing) {
            asyncDBCall(function() {
                result.someOtherThing = somevalue;
                return result;
            });
        }
    });
}

There is another solution which allows both requests to be sent simultaneously. 还有另一种解决方案,允许同时发送两个请求。

var someFlag = false, someOtherFlag = false;
if (filters.something) {
    asyncDBCall(function() {
        result.something = somevalue;
        someFlag = true;
        if (someFlag && someOtherFlag)
            return result;
    });
}

if (filters.someOtherThing) {
    asyncDBCall(function() {
        result.someOtherThing = somevalue;
        someOtherFlag = true;
        if (someFlag && someOtherFlag)
            return result;
    });
}

If you have many properties in filter object, you need to use recursion. 如果过滤器对象中有许多属性,则需要使用递归。

Use async module. 使用异步模块。 Async.parallel will execute the two queries in parallel. Async.parallel将并行执行两个查询。 Use async.series to execute one after another. 使用async.series一个接一个地执行。

You should consider using JavaScript promises. 您应该考虑使用JavaScript Promise。 When you use them, you'll not have to deal with the callback hell which node.js drives you into. 使用它们时,您不必处理node.js将您带入的回调地狱。

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

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