@optimizely/nuclear-router
Version:
NuclearJS Router
89 lines (83 loc) • 2.67 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* Variant of Promise.race(iterable)
*
* Given a list of Promises, return a Promise which resolves
* with the index of the first Promise in the list which resolves
* AND doesnt explicitly return false,
* ensuring that all Promises before it have been settled.
*
* E.g.:
*
* When the structure of promiseList is:
*
* // [<rejects in 1s>, <resolves in 1s>, <resolved>]
* // => Resolves with #2 after 1s
*
* // [<resolved>, <resolves in 1s>, <resolved>]
* // => Resolves with #1 immediately
*
* // [<rejects in 1s>, <rejected>, <resolved>]
* // => Resolves with #3 after 1s
*
* // [<rejected>, <resolves in 1s>, <resolved>]
* // => Resolves with #2 after 1s
*
* // [<resolves in 2s>, <resolves in 1s>, <resolved>]
* // => Resolves with #1 after 2s
*
* @param {Promise[]} promiseList
* @returns {Promise}
*/
var PromiseOrderedFirst = exports.PromiseOrderedFirst = function PromiseOrderedFirst(promiseList) {
return new Promise(function (resolve, reject) {
var promiseToStateMap = [];
var compute = function compute() {
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = promiseToStateMap[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var _step$value = _step.value,
state = _step$value.state,
res = _step$value.res,
index = _step$value.index;
if (state === "pending") {
return;
} else if (state === "resolved" && res !== false) {
resolve({ res: res, index: index });
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
reject();
};
promiseList.forEach(function (promiseLike, index) {
promiseToStateMap[index] = { state: "pending" };
promiseLike.then(function (res) {
promiseToStateMap[index] = { state: "resolved", res: res, index: index };
}).catch(function (res) {
promiseToStateMap[index] = { state: "rejected", res: res, index: index };
}).then(compute, compute);
});
compute();
});
};
exports.default = {
PromiseOrderedFirst: PromiseOrderedFirst
};