jQuery.waterfall. is very useful

It is a fairly typical task, when the pattern of its solution usually is called as a waterfall. The implementation of this pattern is node.js, although some people work in the browser - async.
But we do not want to include the entire module for a single method as well as the copy / paste. The callback function is passed to async, everywhere we used the jQuery.Deferred. There is no difference, but we do not want to “break” a design style :)
As a result, there is written a small utility similar to jQuery.when
Unlike to the jQuery.when, the functions and their return should be passed by arguments, and not jqxhr, otherwise sense of waterfall will be lost. Although, it will not cause the error, because the waterfall accepts any argument’s types.
It is easy to use it
1. Perform on stage 3 and show the results of the query:
$.waterfall(
function() {
return $.ajax(...)
},
function(arg1) {
return $.ajax(...)
},
function(arg2) {
return $.ajax(...)
}
)
.fail(function(error) {
console.log('fail');
console.log(error);
})
.done(function() {
console.log('success');
console.log(arguments);
})
2. Let us make one query, we verify what was returned and decide what to do next:
$.waterfall(
function() {
return $.ajax(...)
},
function(arg1) {
return arg1 && arg1.answer == 42 ? $.ajax(...) : false;
},
function(arg2) {
return $.ajax(...)
}
)
.fail(function(error) {
console.log('fail');
console.log(error)
})
.done(function() {
console.log('success');
console.log(arguments)
})
3. Waterfall can accept any types of argument. False will be interrupted by the waterfall immediately, the rest of values are different from the functions and deferred objects will be added to the result:
var dfrd = $.Deferred();
$.waterfall(
function() {
return $.ajax(...)
},
$.ajax(...), / / will be performed “out-of-order”
dfrd, / / series will not end until manually will be done resolve / reject
'string',
42,
false / / always finishes series error
)
.fail(function(error) {
console.log('fail');
console.log(error)
})
.done(function() {
console.log('success');
console.log(arguments)
})
That is all. The criticism and advice are welcome.
The code is on githab
![]() |
![]() |
|
Vote for this post
Bring it to the Main Page |
||
![]() |
![]() |
Comments
Leave a Reply