Created
October 6, 2017 15:06
-
-
Save eip/09adf0c9e10675bf13989acff56fa550 to your computer and use it in GitHub Desktop.
Promises example: Race to success
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Logging helpers | |
var _startTime; | |
function _log() { // calling: _log.apply(console.log, arguments); | |
var nowTime = new Date(); | |
var args = Array.prototype.slice.call(arguments, 0); | |
// var log = args.pop(); | |
if (!_startTime) _startTime = nowTime; | |
args.unshift((' ' + (nowTime - _startTime)).slice(-5), 'ms:'); | |
this(args.join(' ')); | |
} | |
function logInfo() { | |
_log.apply(console.log, arguments); | |
} | |
function logError() { | |
_log.apply(console.error, arguments); | |
} | |
// -------------------- | |
function mockRequest(result, timeout, success) { | |
return new Promise(function(resolve, reject) { | |
setTimeout(function() { | |
if (success) { | |
logInfo('+++ Resolving promise [' + result + ']'); | |
resolve(result) | |
} else { | |
logInfo('xxx Rejecting promise [' + result + ']'); | |
reject(result); | |
}; | |
}, timeout); | |
}); | |
} | |
function invertPromise(promise) { | |
return new Promise(function (resolve, reject) { promise.then(reject, resolve); }); | |
} | |
function raceToSuccess(promises) { | |
return invertPromise(Promise.all(promises.map(invertPromise))); | |
} | |
// -------------------- | |
function _mockRequest(result, timeout, success) { | |
var p; | |
} | |
logInfo('Starting...'); | |
// mockRequest('Request 01 succeded', 500, true).then(logInfo, logError); | |
// mockRequest('Request 02 failed', 550, false).then(logInfo, logError); | |
// invertPromise(mockRequest('Request 03 succeded inverted', 600, true)).then(logInfo, logError); | |
// invertPromise(mockRequest('Request 04 failed inverted', 650, false)).then(logInfo, logError); | |
var requests = []; | |
var success; | |
var timeout = 0; | |
for (var i = 0; i < 5; ++i) { | |
success = Math.random() >= .5; | |
timeout += Math.round(Math.random() * 50 + 1) * 10; | |
requests.push(mockRequest('Request ' + ('0' + (i + 1)).slice(-2) + (success ? ' succeded' : ' failed') + '.', timeout, success)); | |
console.log('Request ' + ('0' + (i + 1)).slice(-2) + ' will be' + (success ? ' succeded' : ' failed') + ' in ' + timeout + ' ms.'); | |
} | |
raceToSuccess(requests).then(logInfo, logError); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment