Created
March 11, 2015 11:19
-
-
Save amatiasq/3abbb4f4b9b24b9dcc72 to your computer and use it in GitHub Desktop.
Solves a race condition issue on a Promise function: http://jsfiddle.net/amatiasq/zhmz8xdx/
This file contains 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
function raceCondition(fn) { | |
var counter = 0; | |
return function() { | |
var index = ++counter; | |
var prom = fn.apply(this, arguments); | |
return new Promise(function(resolve, reject) { | |
prom.then(function(value) { | |
if (isLast()) resolve(value); | |
}, function(error) { | |
if (isLast()) reject(error); | |
}) | |
}); | |
function isLast() { | |
return index === counter; | |
} | |
}; | |
} |
This file contains 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
function timeout(ms) { | |
return new Promise(function(resolve, reject) { | |
setTimeout(resolve, ms); | |
}); | |
} | |
var rcTimeout = raceCondition(timeout); | |
rcTimeout(1000).then(function() { console.log(1) }); | |
rcTimeout(500) .then(function() { console.log(2) }); | |
rcTimeout(100) .then(function() { console.log(3) }); | |
rcTimeout(50) .then(function() { console.log(4) }); | |
rcTimeout(100) .then(function() { console.log(5) }); | |
// Only output: 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment