Example on how to use race on Promise. It resolves or reject whenever any of the concurrently running tasks are completed. Example is using expect library for assertion
A Pen by Vlad Bezden on CodePen.
Example on how to use race on Promise. It resolves or reject whenever any of the concurrently running tasks are completed. Example is using expect library for assertion
A Pen by Vlad Bezden on CodePen.
'use strict'; | |
/** | |
* Increment a given value | |
* @param {Number} val | |
* @returns {Promise} | |
*/ | |
const foo = (val) => { | |
return new Promise((resolve) => { | |
setTimeout(() => { | |
resolve(val + 1); | |
}, 100); | |
}); | |
}, | |
/** | |
* Increment a given value | |
* @param {Number} val | |
* @returns {Promise} | |
*/ | |
bar = (val) => { | |
return new Promise((resolve) => { | |
setTimeout(() => { | |
resolve(val + 2); | |
}, 200); | |
}); | |
}; | |
Promise.race([foo(1), bar(2)]).then((arr) => { | |
expect(arr).toEqual(2); | |
}); | |
console.log('All Tests Passed!'); |
<script src="https://npmcdn.com/expect/umd/expect.min.js"></script> |