Skip to content

Instantly share code, notes, and snippets.

@donabrams
Created December 7, 2019 08:40
Show Gist options
  • Save donabrams/d82fef7874da544df9ad71d9bd5fd8b8 to your computer and use it in GitHub Desktop.
Save donabrams/d82fef7874da544df9ad71d9bd5fd8b8 to your computer and use it in GitHub Desktop.
Async Produce/Consume Channel
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