Repository navigation
Expand file tree
/
Copy pathexample.cjs
More file actions
48 lines (42 loc) · 1.44 KB
/
Copy pathexample.cjs
File metadata and controls
48 lines (42 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
const {
createSyncHook,
createAsyncHook
} = require('../dist/index.umd.cjs')
const syncHook = createSyncHook() // series by default
syncHook.tap(message => console.log(`Sync Message: ${message}`))
syncHook.call('Hello')
const asyncHook = createAsyncHook() // series by default
asyncHook.tap(async message => console.log(`Async Message: ${message}`))
// A `.cjs` file has no top-level await, so the async call is awaited inside a wrapper.
// Without this the whole sample fails to parse: `node samples/example.cjs` threw
// "await is only valid in async functions", including in the published 0.1.2.
void (async () => {
await asyncHook.call('Hello').catch(e => console.error(e))
})()
const waterfallHook = createSyncHook({ type: 'waterfall' })
waterfallHook.tap(value => value + '+1')
waterfallHook.tap(value => value + '+2')
waterfallHook.tap(value => value + '+3')
const waterfallResult = waterfallHook.call('Hello')
console.log(waterfallResult) // 'Hello+1+2+3"
const bailHook = createSyncHook({ type: 'bail' })
bailHook.tap(value => {
console.log("tap1")
})
bailHook.tap(value => {
console.log("tap2")
return "2"
})
bailHook.tap(value => {
console.log("tap3")
})
// prints "tap1", "tap2, and then returns "2"
const bailResult = bailHook.call()
const interceptHook = createSyncHook()
interceptHook.intercept({
tap: (info) => {
console.log('interceptHook was tapped by ' + info.name)
}
})
interceptHook.tap({ name: 'the tapper' }, () => {
})