v2.0.0
The document
OneHandle allows you to create 4 time-sensitive caches
- OneHandle (FN): Concurrency timeliness
- OneHandle (fn, true) : Memory timeliness (e.g., no page refresh)
- OneHandle (fn, ‘local cache key name ‘, ‘sessionStorage’): sessionStorage validity
- OneHandle (fn, ‘local cache key name ‘): localStorage timeliness
background
Before, I heard a sharing meeting with my colleague. In one scenario, the parent module needs the data of an interface, and the child module also needs the data of this interface. If both the child and parent modules tune this interface, the performance will be wasted. You can also use vuex, props. Using Vuex would be too cumbersome and cumbersome to reuse to other projects. For now, props is the best, but sometimes other methods need to be used for other background reasons.
I came up with a way to write by queue, and then I consulted the elder brothers and sisters (the reaction was very warm, applause).
So, what do you want to do with a queue, which is to process the function that comes in through a closure, and return a wrapped function, and how do you use the function before, and how do you use the wrapped function, zero contamination
The wheel profile
One-handle invokes multiple times and responds once, enabling cache
A one-handle function that accepts a return Promise generates a closure that caches a queue. When called concurrently, only one function will be triggered at the same time. Subsequent functions will be placed in the queue waiting for the completion of the first function. The first Promise state also affects the state in the queue (resolve or Reject).
use
Download the way
npm i one-handle
yarn add one-handle
// Import mode
// esm
import oneHandle from 'one-handle'
// script
<script src="https://unpkg.com/one-handle"></script>
window.oneHandle
Copy the code
use
import oneHandle from 'one-handle'
function wait (time, data = 0) {
return new Promise(resolve= > {
setTimeout(() = > resolve(data), time)
})
}
const $wait1 = oneHandle(wait)
$wait1(1000.1).then(data= > console.log('Trigger only once', data)) // Only trigger 1 once
$wait1(4000.2).then(data= > console.log('Trigger only once', data)) // Only trigger 1 once
$wait1(1.3).then(data= > console.log('Trigger only once', data)) // Only trigger 1 once
// To use caching, pass the second argument true
const $wait2 = oneHandle(wait, true)
// The value returned by the first successful call will be cached, and the next call will take that value
$wait2(1.false).then(data= > {
console.log('Cache it', data) // cache false
return $wait2(1.50)
})
.then(data= > console.log('Use cache', data)) // Use cache false
Copy the code
parameter
/** * multiple calls, response once, can open cache **@param {Function} Fn a function that returns Promise *@param {Boolean} Cache Whether cache is enabled *@param {*} Context *@returns {Function} Return Promise closure */
function oneHandle (fn, cache, context) {
Copy the code
The end
Github.com/hengshanMWC…