Last active
October 26, 2018 23:56
-
-
Save redgeoff/b5261be6791b0768c52d06a98a256377 to your computer and use it in GitHub Desktop.
Synchronizer - basic synchronization using promise chaining
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
<script> | |
let synchronizer = Promise.resolve(); | |
function synchronize(promiseFactory) { | |
const promise = synchronizer.then(() => { | |
return promiseFactory(); | |
}); | |
synchronizer = synchronizer.then(() => promise); | |
return promise; | |
} | |
function timeout(milliseconds) { | |
return new Promise((resolve) => { | |
setTimeout(resolve, milliseconds); | |
}); | |
} | |
synchronize(() => { | |
return timeout(300).then(function () { | |
console.log('done with 300 ms timeout'); | |
}); | |
}); | |
synchronize(() => { | |
return timeout(100).then(function () { | |
console.log('done with 100 ms timeout'); | |
}); | |
}); | |
</script> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment