kobesin
kobesin

Reputation: 15

How to create non-blocking asynchronous function in node.js and express.js

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

Upvotes: 0

Views: 1590

Answers (2)

Ben
Ben

Reputation: 5074

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

Upvotes: 3

Jarema
Jarema

Reputation: 3586

If You like, You dont have to use any external libraries. You can do for example something like this:

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

You can test it, and see, that "2" will be printer after 1 and 3. Hope it helped.

PS You can also use setInterval, or Underscore library:

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

Upvotes: 1

Related Questions