lei-mu / single-promises Goto Github PK
View Code? Open in Web Editor NEWCreate a singleton pattern Promise-invoking function
License: ISC License
Create a singleton pattern Promise-invoking function
License: ISC License
源码:https://github.com/lei-mu/single-promises/blob/master/lib/index.js
import {version} from '../package.json'
/**
* 用于包装一个函数并返回一个新函数,使其调用这个新函数只有一个promise在执行,后续的调用都会返回这个promise
* @param fn {function(...[*]): (Promise<Awaited<*>>)} - 需要包装的函数
* @param opt {object} - 配置项
* @param opt.cache {number} [opt.cache = 0] - 缓存时间,单位毫秒,如果大于0,则会缓存结果,下次调用如何结果仍在有效缓存时间内,则会直接返回缓存的结果。默认0,不缓存
* @return {(function(...[*]): (Promise<Awaited<*>>))|*}
*/
function singlePromise(fn, opt = {}) {
const defaultOpt = {
cache: 0
}
let promise
let cacheMill = -1
let cacheRes
opt = Object.assign({}, defaultOpt, opt)
function handle(...args) {
let self = this
let {cache} = opt
if (cache && cacheMill > 0) {
if (Date.now() - cacheMill < cache) {
return Promise.resolve(cacheRes)
} else {
cacheMill = -1
cacheRes = null
}
}
if (promise) {
return promise
} else {
promise = Promise.resolve(fn.apply(self, args))
}
return promise.then((res) => {
if (cache) {
cacheMill = Date.now()
cacheRes = res
}
promise = null
return res
}).catch((err) => {
promise = null
return Promise.reject(err)
})
}
handle.clear = function () {
cacheMill = -1
cacheRes = null
}
handle.update = function (newOpt = {}) {
opt = Object.assign({}, opt, newOpt)
}
return handle
}
export {
singlePromise,
version
}
上面是我js 工具库的实现。
我需要index.d.ts 实现。
使用示例
const getTime = (t) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(Date.now() * t)
}, 1000)
})
}
const singleOptions = {
cache: 0
}
const singleGetTime = singlePromise(getTime, singleOptions)
for (let i = 0; i < 5; i++) {
// 希望调用 时能有参数提示,参数同getTime
singleGetTime(3).then((res) => {
console.log('res', res)
})
}
// 希望能有 clear 方法提示
singleGetTime.clear()
const newSingleOptions = {
cache: 1
}
// 希望能有 update 方法提示、参数提示
singleGetTime.update(newSingleOptions)
// fn 支持同步函数。
const getTime2 = (str) => {
return Date.now() + str
}
// fn 可以是同步函数,但singlePromise 函数返回的函数,调用时永远返回promise
const singleGetTime2 = singlePromise(getTime2)
singleOptions 是可选的。singleOptions.cache 是number,也是可选的
singlePromise 的第一个参数 fn 必传,函数类型。
fn 可以是同步函数,也可以是promise
singlePromise 的第二个参数是 singleOptions ,非必填。
singlePromise 调用时,返回一个函数 handle
handle 接收的参数会传递给 fn。
handle 调用 返回值是一个Promise
Promise(别名:p1) 的返回值取决于 fn。fn 的返回值会被 Promise.resolve 包裹。响应表现如Promise.resolve
如果fn 是一个同步函数,那 fn 的返回值 会在 Promise 结果 体现
如果fn 返回一个Promise(别名:p2),那p1 的相应状态取决于 p2 的相应状态。
handle.update 一个参数,非必传。参数类型为 singleOptions。为一个函数
handle.clear 无参数。为一个函数
调用handle 时希望有fn 的参数提示,和返回值提示
5.singleGetTime 作为函数调用时,参数和 返回值同 fn,不同的是fn 不一定返回promise,但 singleGetTime 作为函数调用时,返回值一定是Promise,值类型同 fn 的返回值类型
以下是我的一些尝试,但是似乎达不到想要的效果
declare module 'single-promises' {
export interface SingleOptions {
cache?: number;
}
type FunctionType<T> = (...args: any[]) => T extends Promise<infer U> ? Promise<U> : Promise<T>;
export interface SinglePromiseHandle<T> {
(...args: Parameters<FunctionType<T>>): ReturnType<FunctionType<T>>;
clear(): void;
update(newOpt?: SingleOptions): void;
}
export function singlePromise<T>(fn: FunctionType<T>, opt?: SingleOptions): SinglePromiseHandle<T>;
export const version: string;
}
如果需要提交pr, 请合并至 ts
分支
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.