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.
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.
| '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> |