Question

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
}) 
Was it helpful?

Solution 2

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

OTHER TIPS

Yes, well kind of. The chain would need to be differently constructed :

obj.function1().then(obj.function2).then(obj.function3);
  • function1 would need to return a resolved/resolvable promise.

  • function2 (or all intermediate functions) would need to return a result or a new resolved/resolvable promise.

  • function3 (or whichever function comes last) would need to do something with the accumulated result of the earlier functions in the chain - ie. it must be a "consumer" function.

As promises have a mechanism for rejection as well as resolution, a promise-chain offers greater inherent possibilities than chainsaw, to allow/terminate progress down the chain.

As the promise interface includes methods other than .then(), further flexibility is also provided.

That said, I've not looked at chainsaw before, so I've not really got my mind round its full potential.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top