5

Is it possible to create chained methods that are asynchronous like this in node.js

File.create('file.jpg').rename('renamed.jpg').append('Hello World')

That is to say non-blocking.

700 Software
  • 85,281
  • 83
  • 234
  • 341
ajsie
  • 77,632
  • 106
  • 276
  • 381
  • If it's non-blocking, shouldn't there be a callback function passed in somewhere? – Matthew Flaschen Nov 08 '10 at 06:31
  • @Matthew: Yeah it should. So I wonder if there is some way to create a method chaining that is asynch. Maybe with a library that could handle it automatically somehow. – ajsie Nov 08 '10 at 06:48

2 Answers2

8

You basically want to abstract the asynchronous nature of the file-handling operations on your API.

It can be done, I would recommend you to give a look to the following article:

The article was written by Dustin Diaz, who currently works on the @anywhere JavaScript API, and he does exactly what you want, using a using a simple Queue implementation, a fluent interface can be created, being independent of any callback.

The asynchronicity is hidden and it is handled internally by your API, it's a nice and simple technique.

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
0

Sure, like any JavaScript, you just return an object that has that method.

One possible layout (among many).

var File = new (function() 
{ 
  this.create = function(str) 
  { 
    return this; 
  } 
  this.rename = function(str) 
  { 
    return this; 
  } 
})(); 
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
  • 1
    Sorry I forgot to tell you that the code has to be asynchronous in Node.js. I have edited the post. – ajsie Nov 08 '10 at 06:27