javascript control-flow tool that allows execution of async code step by step.
How to use
var z =require('zen-then')();
z.then(function(){
console.log('1...');
returnz.result('one');
}).then(function(x){
console.log('2...');
console.log('1st function result: ', x);
setTimeout(function(){
console.log('x=', x);
returnz.result(x+' plus one');
},1000);
}).then(function(x){
console.log('3...');
console.log('result from second function: ', x);
returnz.result();
});
It's important to explicitly call return z.result(...) after each function.
returnz.result('some return value');
returnz.result('string',123,x);//few values can be returned
returnz.result();//just continue to the next function
To use returned values in the next function:
var z =require('zen-then')();
z.then(function(){
returnz.result(1,2,3);
}).then(function(a,b,c){
console.log(a,b,c);
returnz.result();
});
There are some aliases for z.result():
returnz.result(...);
returnz.ok(...);//same as z.result(...);
returnz.return(...);//same as z.result(...);
Exception handling
Execute return z.exception(myExceptionObject) to throw exception and stop execution.
This is not the same exception as in throw myException.
Use .catch(function(exception){ ... }) method to catch exception from any function.
var z =require('zen-then')();
z.then(function(){
console.log('1...');
returnz.result('one');
}).then(function(x){
console.log('2...');
console.log('1st function result: ', x);
setTimeout(function(){
console.log('x=', x);
returnz.exception('X');//let's throw exception
},1000);
}).then(function(x){
// this function will not be executed
console.log('3...');
console.log('result from second function: ', x);
returnz.result();
}).catch(function(exception){
console.log('catching exception: ', exception);
});
Method .catch(function(exception){ ... } can catch usual exception also, but only for synchronous functions.
So you must exlicitly call return z.exception(...) when hadling usual exception in asynchronous functions.
Aliases for return z.exception(...).
returnz.exception(x);
returnz.error(x);//same
returnz.fail(x);//same
Alias for .catch is .onError:
.catch(function(exception){...});
.onError(function(exception){...});//same
Warnings
You can throw warning messages with z.warning('message') and catch them later with
.eachWarning(function(warning){ ... }) or with .getAllWarnings(function(allWarnings){ ... }).
All warnings handling occurs after all functions will be executed or before any exception handling.