Created
April 9, 2019 12:35
-
-
Save giordanocardillo/a78ee10dadcf0b20df9046314f107aa4 to your computer and use it in GitHub Desktop.
Promise Synchronize
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
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