Skip to content

Instantly share code, notes, and snippets.

@redgeoff
Last active October 26, 2018 23:56
Show Gist options
  • Save redgeoff/b5261be6791b0768c52d06a98a256377 to your computer and use it in GitHub Desktop.
Save redgeoff/b5261be6791b0768c52d06a98a256377 to your computer and use it in GitHub Desktop.
Synchronizer - basic synchronization using promise chaining
<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