Created
December 7, 2019 08:40
-
-
Save donabrams/d82fef7874da544df9ad71d9bd5fd8b8 to your computer and use it in GitHub Desktop.
Async Produce/Consume Channel
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 channel() { | |
const buffer = []; | |
const wait = []; | |
let lastSignal; | |
const consume = function() { | |
return buffer.length > 0 | |
? Promise.resolve(buffer.shift()) | |
: new Promise((resolve) => { | |
wait.push((val) => resolve(val)); | |
}); | |
}; | |
const signal = function() { | |
if (wait.length && buffer.length) { | |
const next = buffer.shift(); | |
const waiter = wait.shift(); | |
waiter(next); | |
} | |
}; | |
const produce = function(val) { | |
console.log(val); | |
lastSignal = val; | |
buffer.push(val); | |
signal(); | |
}; | |
return { | |
produce, | |
consume, | |
getLastSignal: () => lastSignal, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment