Simplify implementation of select
.
This commit is contained in:
parent
ea2cc74711
commit
3ff3031b1e
2 changed files with 37 additions and 37 deletions
24
lib/index.js
24
lib/index.js
|
@ -403,10 +403,12 @@ Channel.of = (...values) => Channel.from(values);
|
|||
Channel.isChannel = arg =>
|
||||
arg !== undefined && arg !== null && Object.getPrototypeOf(arg) === prototype;
|
||||
|
||||
Channel.select = methodPromises =>
|
||||
Object.assign(
|
||||
new Promise((resolve, reject) => {
|
||||
try {
|
||||
Channel.select = methodPromises => {
|
||||
if (!Array.isArray(methodPromises)) {
|
||||
throw new TypeError(`Channel.select: Argument must be an array.`);
|
||||
}
|
||||
|
||||
const selectPromise = new Promise((resolve, reject) => {
|
||||
methodPromises.forEach(async promise => {
|
||||
try {
|
||||
promise.prethen(() => {
|
||||
|
@ -434,14 +436,12 @@ Channel.select = methodPromises =>
|
|||
);
|
||||
}
|
||||
});
|
||||
} catch (exception) {
|
||||
reject(new TypeError(`Channel.select: Argument must be an array.`));
|
||||
}
|
||||
}),
|
||||
{
|
||||
cancel: () => Promise.all(methodPromises.map(promise => promise.cancel()))
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
return Object.assign(selectPromise, {
|
||||
cancel: () => methodPromises.forEach(promise => promise.cancel())
|
||||
});
|
||||
};
|
||||
|
||||
// functional interface allowing full or partial application
|
||||
//
|
||||
|
|
|
@ -98,6 +98,7 @@ describe(`Channel function`, function() {
|
|||
it(`miscellaneous`, async function() {
|
||||
const a = Channel();
|
||||
const b = Channel();
|
||||
|
||||
(async () => {
|
||||
await b.push(0);
|
||||
await a.push(1);
|
||||
|
@ -114,10 +115,9 @@ describe(`Channel function`, function() {
|
|||
it(`allows for non-blocking selects`, async function() {
|
||||
const a = Channel();
|
||||
const b = Channel();
|
||||
const closed = Channel.of();
|
||||
|
||||
switch (
|
||||
await Channel.select([a.shift(), b.push(0), Channel.of().shift()])
|
||||
) {
|
||||
switch (await Channel.select([a.shift(), b.push(0), closed.shift()])) {
|
||||
case a:
|
||||
assert(false);
|
||||
break;
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue