3 ms·
You might as well avoid wrapping the types and just split the writer and reader: it's good practice to do this anyway, since you probably only need one half of
by vore 4y ago
You might as well avoid wrapping the types and just split the writer and reader: it's good practice to do this anyway, since you probably only need one half of the oneshot channel on each side and having a handle to something that can both read and write seems like a logic error. You can also augment the writer function to throw into the promise, if required!
type Sender<T, E = unknown> = ((e: null, v: T) => void) & ((e: E) => void);
function oneshot<T, E = unknown>(): [Promise<T>, Sender<T, E>] {
let send: Sender<T, E>;
const recv = new Promise<T>((resolve, reject) => {
send = (err, v?: T) => err == null ? resolve(v!) : reject(err);
});
return [recv, send!];
}