-
Notifications
You must be signed in to change notification settings - Fork 29.8k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
lib: make AbortSignal cloneable/transferable
Allows for using `AbortSignal` across worker threads and contexts. ```js const ac = new AbortController(); const mc = new MessageChannel(); mc.port1.onmessage = ({ data }) => { data.addEventListener('abort', () => { console.log('aborted!'); }); }; mc.port2.postMessage(ac.signal, [ac.signal]); ``` Signed-off-by: James M Snell <[email protected]>
- Loading branch information
Showing
2 changed files
with
143 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
'use strict'; | ||
|
||
const common = require('../common'); | ||
const { ok, strictEqual } = require('assert'); | ||
|
||
{ | ||
const ac = new AbortController(); | ||
const mc = new MessageChannel(); | ||
mc.port1.onmessage = common.mustCall(({ data }) => { | ||
data.addEventListener('abort', common.mustCall(() => { | ||
strictEqual(data.reason, 'boom'); | ||
})); | ||
}, 2); | ||
mc.port2.postMessage(ac.signal, [ac.signal]); | ||
|
||
// Can be cloned/transferd multiple times and they all still work | ||
mc.port2.postMessage(ac.signal, [ac.signal]); | ||
|
||
mc.port2.close(); | ||
|
||
// Although we're using transfer semantics, the local AbortSignal | ||
// is still usable locally. | ||
ac.signal.addEventListener('abort', common.mustCall(() => { | ||
strictEqual(ac.signal.reason, 'boom'); | ||
})); | ||
|
||
ac.abort('boom'); | ||
} | ||
|
||
{ | ||
const signal = AbortSignal.abort('boom'); | ||
ok(signal.aborted); | ||
strictEqual(signal.reason, 'boom'); | ||
const mc = new MessageChannel(); | ||
mc.port1.onmessage = common.mustCall(({ data }) => { | ||
ok(data instanceof AbortSignal); | ||
ok(data.aborted); | ||
strictEqual(data.reason, 'boom'); | ||
mc.port1.close(); | ||
}); | ||
mc.port2.postMessage(signal, [signal]); | ||
} | ||
|
||
{ | ||
// The cloned AbortSignal does not keep the event loop open | ||
// waiting for the abort to be triggered. | ||
const ac = new AbortController(); | ||
const mc = new MessageChannel(); | ||
mc.port1.onmessage = common.mustCall(); | ||
mc.port2.postMessage(ac.signal, [ac.signal]); | ||
mc.port2.close(); | ||
} |