Code Monkey home page Code Monkey logo

single-promises's Issues

需要index.d.ts 实现

源码: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)
  1. singleOptions 是可选的。singleOptions.cache 是number,也是可选的

  2. singlePromise 的第一个参数 fn 必传,函数类型。

    fn 可以是同步函数,也可以是promise

  3. singlePromise 的第二个参数是 singleOptions ,非必填。

  4. 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 分支

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.