select: Make promise cancellable.
This commit is contained in:
parent
03ebfaf7ab
commit
67012b6f4b
3 changed files with 36 additions and 23 deletions
|
@ -85,6 +85,9 @@ Returns a version of the channel that provides only write methods.
|
|||
returns the channel of the first one that succeeds. Only the winning method is
|
||||
executed to completion—the other methods have no effect.
|
||||
|
||||
All of the methods can be cancelled before completion by calling `cancel` on the
|
||||
promise returned from `select`.
|
||||
|
||||
#### Examples
|
||||
|
||||
Imagine you're at a party and your next conversation depends on whom you run
|
||||
|
|
15
lib/index.js
15
lib/index.js
|
@ -309,8 +309,9 @@ Channel.of = (...values) =>
|
|||
Channel.isChannel = (arg) =>
|
||||
prototype.isPrototypeOf(arg)
|
||||
|
||||
Channel.select = (...methodPromises) => {
|
||||
const promise = new Promise((resolve, reject) => {
|
||||
Channel.select = (...methodPromises) =>
|
||||
Object.assign(
|
||||
new Promise((resolve, reject) => {
|
||||
methodPromises.forEach(async (promise) => {
|
||||
promise.prethen(() => {
|
||||
// We've been given a heads-up that this method will complete first so
|
||||
|
@ -330,10 +331,12 @@ Channel.select = (...methodPromises) => {
|
|||
|
||||
resolve(promise.channel)
|
||||
})
|
||||
})
|
||||
|
||||
return promise
|
||||
}
|
||||
}),
|
||||
{
|
||||
cancel: () =>
|
||||
Promise.all(methodPromises.map((promise) => promise.cancel()))
|
||||
}
|
||||
)
|
||||
|
||||
// functional interface allowing full or partial application
|
||||
//
|
||||
|
|
|
@ -118,6 +118,13 @@ describe(`Channel`, function () {
|
|||
break
|
||||
}
|
||||
})
|
||||
|
||||
it(`cancel`, async function () {
|
||||
const channel = Channel()
|
||||
Channel.select(channel.push(`cancelled`)).cancel()
|
||||
const closed = Channel.of()
|
||||
assert.equal(await Channel.select(channel.shift(), closed.shift()), closed)
|
||||
})
|
||||
})
|
||||
|
||||
describe(`functional interface`, async function () {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue