【问题标题】:How to create non-blocking asynchronous function in node.js and express.js如何在 node.js 和 express.js 中创建非阻塞异步函数
【发布时间】:2014-07-08 13:42:39
【问题描述】:

我通过 WebMatrix 创建 express.js 示例。我想创建一个 api 来从 myfunction 获取结果。如果第一个请求案例复杂且花费大量时间,而第二个请求案例简单,则第二个请求必须等待第一个请求完成。我可以做一些第二个请求可以比第一个请求更快地返回数据的事情吗?

app.post('/getData', function(req, res) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header("Access-Control-Allow-Headers", "X-Requested-With");
   var case= req.body.case;
   var json = myfunction(case);
   res.json(json);
});

【问题讨论】:

  • case不是保留字吗?
  • 看看async库。
  • 我建议您查看cluster API - 将您的逻辑划分为简单和苛刻的请求并创建一些child processes

标签: node.js express


【解决方案1】:

您可以使用 async 来实现:

var async = require('async');

async.waterfall([
  function(callback){  // first task

    // process myCase (don't use case, it's reserved word), 
    // then pass it to your next function


    callback(null, myCase); // 1st argument: null means no error
                            // if error, pass error in 1st arg
                            // so that 2nd function won't be
                            // executed

  },
  function(myCase, callback){   // 2nd task
    // use argument 'myCase' to populate your final json result (json)
    // and pass the result down in the callback

    callback(null, json);
  }
], function (err, json) {   
    // the argument json is your result

    res.json(json);
});

【讨论】:

    【解决方案2】:

    如果您愿意,您不必使用任何外部库。例如,您可以执行以下操作:

    console.log('1');
    
    function async(input, callback) {
    
        setTimeout(function() {
    
            //do stuff here
            for (var i = 0; i < input; i++) {
                //this takes some time
            }
            //call callback, it may of course return something
            callback('2');
        }, 0);
    
    }
    
    async('10000000', function(result) {
        console.log(result);
    });
    
    
    console.log('3');
    

    你可以测试一下,看看“2”在1和3之后是打印机。 希望对您有所帮助。

    PS 你也可以使用 setInterval 或 Underscore 库:

    var _ = require('underscore');
    
    
    console.log('1');
    
    function async(input, callback) {
    
        _.defer(function() {
            //do stuff here, for ie - this time-consuming loop
            for (var i = 0; i < input; i++) {
                //this takes some time
            }
            //call callback, it may of course return something
            callback('2');
        });
    }
    
    async('10000000', function(result) {
        console.log(result);
    });
    
    
    console.log('3');
    

    【讨论】:

      猜你喜欢
      • 2011-02-22
      • 2013-06-24
      • 2018-04-06
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      • 2020-11-09
      相关资源
      最近更新 更多