Skip to content

Instantly share code, notes, and snippets.

@vlad-bezden
Created January 23, 2016 19:47
Show Gist options
  • Save vlad-bezden/bb8ca455f63c6ee255c6 to your computer and use it in GitHub Desktop.
Save vlad-bezden/bb8ca455f63c6ee255c6 to your computer and use it in GitHub Desktop.
Chaining Promises

Chaining Promises

Example on how to chain Promises. We can pipe the callbacks to queue asynchronous tasks or transform values. Examples are done using expect library

A Pen by Vlad Bezden on CodePen.

License.

'use strict';
/**
* Increment a given value
* @param {Number} val
* @returns {Promise}
*/
const foo = (val) => {
/**
* Return a promise.
* @param {Function} resolve
* @param {Function} reject
*/
return new Promise((resolve, reject) => {
if (!val) {
return reject(new RangeError("Value must be greater than zero"));
}
setTimeout(() => {
resolve(val + 1);
}, 0);
});
};
const testFunctionToTest = () => {
let result = foo(1).then((val) => {
// chaining async call
return foo(val);
}).then((val) => {
// transforming output
return val + 2;
}).then((val) => {
expect(val)
.toEqual(5);
}).catch((err) => {
console.error("Error caught: ", err.message);
});
};
testFunctionToTest();
console.log('All Tests Passed!');
<script src="https://npmcdn.com/expect/umd/expect.min.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment