Create chained methods in node.js?

我们两清 提交于 2019-12-04 12:45:49

问题


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.


回答1:


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:

  • Asynchronous method queue chaining in JavaScript

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.




回答2:


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


来源:https://stackoverflow.com/questions/4121659/create-chained-methods-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!