What is wrappy?
The wrappy npm package is a simple utility module designed to wrap asynchronous functions. It ensures that the callback provided to the wrapped function is only called once, which can be useful in preventing issues where a callback might accidentally be called multiple times due to programming errors.
Callback wrapping
This code demonstrates how to use wrappy to wrap a callback function so that it can only be called once. The 'once' function wraps the provided function 'fn' using wrappy, ensuring that subsequent calls to 'wrapped' after the first one have no effect.
const wrappy = require('wrappy')
function once (fn) {
return wrappy(function () {
if (fn === null) return
var callFn = fn
fn = null
callFn.apply(this, arguments)
})
}
var wrapped = once(function (a) {
console.log('Called with', a)
})
wrapped('first call')
wrapped('second call') // This will not be called