[6a3a178] | 1 | # once
|
---|
| 2 |
|
---|
| 3 | Only call a function once.
|
---|
| 4 |
|
---|
| 5 | ## usage
|
---|
| 6 |
|
---|
| 7 | ```javascript
|
---|
| 8 | var once = require('once')
|
---|
| 9 |
|
---|
| 10 | function load (file, cb) {
|
---|
| 11 | cb = once(cb)
|
---|
| 12 | loader.load('file')
|
---|
| 13 | loader.once('load', cb)
|
---|
| 14 | loader.once('error', cb)
|
---|
| 15 | }
|
---|
| 16 | ```
|
---|
| 17 |
|
---|
| 18 | Or add to the Function.prototype in a responsible way:
|
---|
| 19 |
|
---|
| 20 | ```javascript
|
---|
| 21 | // only has to be done once
|
---|
| 22 | require('once').proto()
|
---|
| 23 |
|
---|
| 24 | function load (file, cb) {
|
---|
| 25 | cb = cb.once()
|
---|
| 26 | loader.load('file')
|
---|
| 27 | loader.once('load', cb)
|
---|
| 28 | loader.once('error', cb)
|
---|
| 29 | }
|
---|
| 30 | ```
|
---|
| 31 |
|
---|
| 32 | Ironically, the prototype feature makes this module twice as
|
---|
| 33 | complicated as necessary.
|
---|
| 34 |
|
---|
| 35 | To check whether you function has been called, use `fn.called`. Once the
|
---|
| 36 | function is called for the first time the return value of the original
|
---|
| 37 | function is saved in `fn.value` and subsequent calls will continue to
|
---|
| 38 | return this value.
|
---|
| 39 |
|
---|
| 40 | ```javascript
|
---|
| 41 | var once = require('once')
|
---|
| 42 |
|
---|
| 43 | function load (cb) {
|
---|
| 44 | cb = once(cb)
|
---|
| 45 | var stream = createStream()
|
---|
| 46 | stream.once('data', cb)
|
---|
| 47 | stream.once('end', function () {
|
---|
| 48 | if (!cb.called) cb(new Error('not found'))
|
---|
| 49 | })
|
---|
| 50 | }
|
---|
| 51 | ```
|
---|
| 52 |
|
---|
| 53 | ## `once.strict(func)`
|
---|
| 54 |
|
---|
| 55 | Throw an error if the function is called twice.
|
---|
| 56 |
|
---|
| 57 | Some functions are expected to be called only once. Using `once` for them would
|
---|
| 58 | potentially hide logical errors.
|
---|
| 59 |
|
---|
| 60 | In the example below, the `greet` function has to call the callback only once:
|
---|
| 61 |
|
---|
| 62 | ```javascript
|
---|
| 63 | function greet (name, cb) {
|
---|
| 64 | // return is missing from the if statement
|
---|
| 65 | // when no name is passed, the callback is called twice
|
---|
| 66 | if (!name) cb('Hello anonymous')
|
---|
| 67 | cb('Hello ' + name)
|
---|
| 68 | }
|
---|
| 69 |
|
---|
| 70 | function log (msg) {
|
---|
| 71 | console.log(msg)
|
---|
| 72 | }
|
---|
| 73 |
|
---|
| 74 | // this will print 'Hello anonymous' but the logical error will be missed
|
---|
| 75 | greet(null, once(msg))
|
---|
| 76 |
|
---|
| 77 | // once.strict will print 'Hello anonymous' and throw an error when the callback will be called the second time
|
---|
| 78 | greet(null, once.strict(msg))
|
---|
| 79 | ```
|
---|