Continuation-passing style
We often need a chain of asynchronous calls, that is, a sequence of tasks where one task is started after another is completed. We are interested in an eventual result of asynchronous calls chain. In this case, we can benefit from
Continuation-passing style (CPS). JavaScript has already a built-in Promise
object. We use it to create a new Promise
object. We put our asynchronous task in the Promise
callback and invoke the resolve
function of the argument list to notify the Promise
callback that the task is resolved:
"use strict"; /** * Increment a given value * @param {Number} val * @returns {Promise} */ var foo = function( val ) { /** * Return a promise. * @param {Function} resolve */ return new Promise(function( resolve ) { setTimeout(function(){ resolve( val + 1 ); }, 0 ); }); }; foo( 1 ).then(function( val ){ console.log( "Result: ", val ); }); // Result: 5
In the...