Chaining promises in JavaScript

Let us have the following promise:

let promise = new Promise(function(resolve, reject) { setTimeout(function() { resolve('string'); }, 3000); });

Upon completion of the promise, we print its result to the console:

promise.then( function(result) { console.log(result); // shows 'string' } )

Now let's not immediately display the result, but somehow change it and return it using return:

promise.then( function(result) { return result + '!'; } );

In this case, we can apply another then to the result of our then, thus creating a chain of methods. In this case, the result of the next method will include what was returned with a return by the previous one:

promise.then( function(result) { return result + '!'; } ).then( function(result) { console.log(result); // shows 'string!' } );

Thus, you can make a chain of any length:

promise.then( function(result) { return result + '1'; } ).then( function(result) { return result + '2'; } ).then( function(result) { return result + '3'; } ).then( function(result) { console.log(result); // shows 'string123' } );
enru