I
I
Ivan2015-07-10 13:28:37
JavaScript
Ivan, 2015-07-10 13:28:37

How to make a function asynchronous in JS?

I study at my leisure Node.JS on the site nodebeginner.ru
One of the points is the implementation of the server response in the "how to" and "how not to" options . I will not give the original code, I will post mine:
app.js (starter)

// modules
var server = require('server');
var router = require('router');
var requestHandlers = require('requestHandlers');

var handle = {};
handle["/"] = requestHandlers.index;
handle["/index.htm"] = requestHandlers.index;
handle["/dir"] = requestHandlers.dir;
handle["/upload"] = requestHandlers.upload;

server.start(router.route, handle);

server.js
var http = require("http");
var url = require("url");

function start(route, handle) {
    function onRequest(request, response) {
        var pathname = url.parse(request.url).pathname;
        // console.log("Request for " + pathname + " received.");

        route(pathname, handle, response);

        // response.writeHead(200, {"Content-Type": "text/plain"});
        // response.write("Hello World");
        // response.end();
    }

    http.createServer(onRequest).listen(1337);
    console.log("Server has started.");
}

exports.start = start;

router.js
function route(pathname, handle, response) {
    // console.log("About to route a request for " + pathname);
    if (typeof handle[pathname] === 'function') {
        return(handle[pathname](response));
    } else {
        response.writeHead(404, {"Content-Type": "text/plain"});
        response.write("File not found.");
        console.log("No request handler found for " + pathname);
    }
}

exports.route = route;

requestHandlers.js
function sleep(callback, milliSeconds) {
    var startTime = new Date().getTime();
    while (new Date().getTime() < startTime + milliSeconds);
    callback();
}

function index(response) {
    // console.log("Request handler 'index' was called.");
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Request handler 'index' was called.");
    response.end();
}


function dir(response) {
    // console.log("Request handler 'index' was called.");
    sleep(function(){
        response.writeHead(200, {"Content-Type": "text/plain"});
        response.write("Request handler 'dir' was called.");
        response.end();
    }, 10000);

}

function upload(response) {
    // console.log("Request handler 'upload' was called.");
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Request handler 'upload' was called.");
    response.end();
}

exports.index = index;
exports.dir = dir;
exports.upload = upload;

Actually, in the "how to" in the guide, it is written that you need to pass the response to requestHandlers.js so that it can be used asynchronously. As a "decelerator" the sleep function is given .
In general, in my case, a miracle did not happen - the application is blocked when going along the /dir path and other requests also wait 10 seconds. Why is that? What have I done wrong?
PS
In the original, for some reason, the author did not consider the solution to this problem, but stupidly took the ready-made exec function and used its callback.
upd.
Alexey Ten : advised to use setTimeout, which worked. But still the question is relevant, how to fix sleep()?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
tex0, 2015-07-10
@LiguidCool

Alexey Ten: advised to use setTimeout

NodeJS has a
process.NextTick(callback(){
//your code
});
There are only two threads running in Node (by default. It seems that you can somehow run additional event loops, but that's a completely different story). The first is the main thread that executes your code, the second is the asynchronous operation processing thread (EventLoop). Until you put your code in the execution queue, it will be executed in synchronous mode, i.e. in the main thread.
process.NextTick queues up your code and immediately returns control to the main thread.
It seems like something like that.
PS: Correct me if I'm wrong somewhere.

A
Alexander Litvinenko, 2015-07-10
@edli007

I remember myself a couple of years ago when I asked the same question.
To answer it, you need to understand how the event loop works.
All functions are synchronous, absolutely everything, but if a function takes too long to execute, it will become a blocking operation.
For example, you are reading a file, if you are reading it all at once, while it is being read, the entire stream of events is frozen in place.
If you read the file asynchronously, then everything happens exactly the same, but the file is read in small pieces, reading one piece is one function and each subsequent function is triggered by an event, and in between events for reading the file, the node will insert events to run other functions.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question