chnwillliu
2020-03-11 09:36:51 +08:00
```
class JSChannel {
constructor() {
this.outputBuffer = [];
this.inputBuffer = [];
}
output() {
if(this.inputBuffer.length) {
const input = this.inputBuffer.shift();
return Promise.resolve(input);
}
const defferred = (() => {
let resolve, reject;
let promise = new Promise((res, rej) => {
resolve = res;
reject = rej;
});
return {
promise,
resolve,
reject
};
})();
this.outputBuffer.push(defferred);
return defferred.promise;
}
input(item) {
if(this.outputBuffer.length) {
const output = this.outputBuffer.shift();
output.resolve(item);
return;
}
this.inputBuffer.push(item);
}
}
```