Thursday 24 November 2016

how to async (non-block) a nodejs function?

I wanted to test some logical things out, before i do a big project in nodejs, and was wondering what is the way to "async" a function.Essentially, suppose i have an api "/getPosts" that might take 2 mins to return data per call...what I am seeing is when 2 calls are sent to /getPosts, the 2nd one will wait until first is resolved.now i know most DB drivers like mongoose, and http libs uses promises to alleviate this...db.get('table').then(function() {});but how does a developer use promises within their code?here is a sample i came up with (widely exaggerated, but illustrates the point)//not really async...but needs to be..ish function asyncFunc() { var stall = 100 * 10000 * 1000 * 10; for(var i = 0; i < stall; i ++) { } } router.get('/', function(req, res, next) { var startDate = new Date(); var xorig = x; if(x === 0) { x = x+1; asyncFunc(); } var endDate = new Date(); var seconds = (endDate.getTime() - startDate.getTime()) / 1000; res.send(' X is : '+ xorig + ' took: '+ seconds.toString()); }); the objective of above is to essentially have 1st request go through the for loop (suppose the user has 1M posts) while the 2nd request is near instant (2nd user has no posts)What i am seeing is that the first request hangs up the process until its done with for loop, then the 2nd request finishes.(on my comp, 1st one takes about ~12secs, next one "theoretically" 0, but in reality 12+X secs)so how do i Async the for loop? such that, 1st user waits until for loop is finished, whereas 2nd user doesnt suffer from delay?

Submitted November 24, 2016 at 04:27PM by T-rex_with_a_gun

No comments:

Post a Comment