Skip to content

Instantly share code, notes, and snippets.

@giordanocardillo
Created April 9, 2019 12:35
Show Gist options
  • Save giordanocardillo/a78ee10dadcf0b20df9046314f107aa4 to your computer and use it in GitHub Desktop.
Save giordanocardillo/a78ee10dadcf0b20df9046314f107aa4 to your computer and use it in GitHub Desktop.
Promise Synchronize
let locked = false
const checkCanCall = (resolve) => {
if (locked) {
return setTimeout(() => checkCanCall(resolve), 100)
}
locked = true
resolve()
};
const waitUntilFree = () => new Promise(checkCanCall)
const unlock = () => locked = false
const synchronize = (action) => {
return waitUntilFree()
.then(() => action())
.finally(unlock)
};
synchronize(() => {
return new Promise((r) =>{
setTimeout(r, 3000);
}).then(r => {
console.info('First Promise, after 3s')
})
}).then(()=>{
console.info('After first promise')
})
synchronize(() => {
return new Promise((r) =>{
setTimeout(r, 3000);
}).then(r => {
console.info('Second Promise, after 6s')
})
}).then(()=>{
console.info('After second promise')
})
console.info('Immediately executed, wait for 3s')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment