一次
只调用一个函数一次。
用法
var once = require('once')
function load (file, cb) {
cb = once(cb)
loader.load('file')
loader.once('load', cb)
loader.once('error', cb)
}
或者添加到函数中。以负责任的方式制作原型:
// only has to be done once
require('once').proto()
function load (file, cb) {
cb = cb.once()
loader.load('file')
loader.once('load', cb)
loader.once('error', cb)
}
具有讽刺意味的是,原型特性使这个模块成为 尽可能复杂。
要检查函数是否已被调用,请使用 fn.called. 一旦
函数第一次调用时返回原函数的返回值
函数保存在 fn.value 随后的电话将继续
返回此值。
var once = require('once')
function load (cb) {
cb = once(cb)
var stream = createStream()
stream.once('data', cb)
stream.once('end', function () {
if (!cb.called) cb(new Error('not found'))
})
}
once.strict(func)
如果函数被调用两次,则抛出错误。
有些函数只被调用一次。使用 once 因为他们会
潜在地隐藏逻辑错误。
在下面的示例中, greet 函数只能调用回调一次:
function greet (name, cb) {
// return is missing from the if statement
// when no name is passed, the callback is called twice
if (!name) cb('Hello anonymous')
cb('Hello ' + name)
}
function log (msg) {
console.log(msg)
}
// this will print 'Hello anonymous' but the logical error will be missed
greet(null, once(msg))
// once.strict will print 'Hello anonymous' and throw an error when the callback will be called the second time
greet(null, once.strict(msg))