What is the best way to build fluent interface in Javascript (node.js) with
obj.function1().function2().function3();
where functions are asynchronous methods?
There is a module called chainsaw, but if it is possilble to do with deferreds and promises (https://github.com/kriskowal/q)
UPD: chain with q.js
obj.function1().then(obj.function2)
//inside obj.function2 "this" context is lost,
//and code is actually broken
obj.function1().then(funciton(){
obj.function2() // <-- "this" context is OK
})
Deferred implementation allows you to do something close, with invoke
:
obj.function1().invoke('function2').invoke('function3');
When ES6 proxies will become a reality, there is a plan to allow same functionality with code below
obj.function1().function2().function3();
but we're not there yet.
Also worth noting is that in Deferred promise
object is actually a function which equals to promise.then
. So plain functions can be chained as:
function1()(function2)(function3);
I hope that's helpful