Bob C
Bob C

Reputation: 61

In this code, why using a closure?

I don't get why a closure is being used in the code below:

function writeData(socket, data){
    var success = !socket.write(data);
    if(!success){
        (function(socket, data){
            socket.once('drain', function(){
                writeData(socket, data);
            });
        })(socket, data)
    }
}

and why using var success=!socket.write(data); instead directly input. May be socket.write is not a boolean?

Upvotes: 0

Views: 73

Answers (2)

robertklep
robertklep

Reputation: 203359

The IIFE is unnecessary, you can rewrite the code to this:

function writeData(socket, data){
  var success = ! socket.write(data);
  if (! success) {
    socket.once('drain', function() {
      writeData(socket, data);
    });
  }
}

Or even this:

function writeData(socket, data){
  var success = ! socket.write(data);
  if (! success) {
    socket.once('drain', writeData.bind(this, socket, data));
  }
}

Upvotes: 2

ZeMoon
ZeMoon

Reputation: 20274

According to the documentation for socket.write(), the method

Sends data on the socket. The second parameter specifies the encoding in the case of a string--it defaults to UTF8 encoding.

Returns true if the entire data was flushed successfully to the kernel buffer. Returns false if all or part of the data was queued in user memory. 'drain' will be emitted when the buffer is again free.

The optional callback parameter will be executed when the data is finally written out - this may not be immediately.

In the code, if the first socket.write() is not able to flush all the data in one go, the closure waits for the socket drain event, in which case it will call writeData method again. This is a very ingenious way of creating an asynchronous recursive function, which will get called until success returns true.

Upvotes: 0

Related Questions