如何在node.js和express.js中创建非阻塞异步函数 [英] How to create non-blocking asynchronous function in node.js and express.js

查看:90
本文介绍了如何在node.js和express.js中创建非阻塞异步函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I create express.js example by WebMatrix. I want to create a api to get result from myfunction. If first request case is complicated and spend many time and the second request case is simple, the second request have to wait the first request finish. Can I do something that the second request can return data faster than first request?

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

推荐答案

您可以使用异步来实现:

You can use async to achieve that:

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

这篇关于如何在node.js和express.js中创建非阻塞异步函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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