npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@retailwe/common-libs-async-queue

v0.0.4

Published

RetailWe libs

Downloads

2

Readme

异步队列模块

需求背景

  • 多个模块之间,需要调用相同的异步请求,为了减少重复请求,使用队列来缓存相同的请求

设计思路

通过内部维护一个队列 Map,不同的 key 对应的不同的请求,同时对外暴露相关方法来操作这个 Map:

export default class AsyncQueue {
  private asyncSet: Map<string, Array<Promise<any>>>;

  constructor() {
    this.asyncSet = new Map<string, Array<Promise<any>>>();
  }

  /**
   * 缓存指定 key 的异步请求
   */
  public setPromise(key: string, anyPromise: Promise<any>): void {
    const cur = this.asyncSet.get(key) || [];
    if (!cur) {
      // 初始化 key: []
      this.asyncSet.set(key, []);
    }
    cur.push(anyPromise);
    this.asyncSet.set(key, cur);
  }

  /**
   * 获取指定 key 的异步请求
   */
  public getPromise(key: string): Promise<any> | undefined {
    let result;
    const queue = this.asyncSet.get(key);
    if (queue && queue.length) {
      result = queue.pop();
    }
    return result;
  }

  /**
   * cachePromise 缓存请求
   * @param key 唯一索引 Key
   * @param fn  异步请求
   */
  public cachePromise<T>(key: string, fn: () => Promise<T>): () => Promise<T> {
    let cachePromise = this.getPromise<T>(key);
    if (!cachePromise) {
      cachePromise = fn();
      this.setPromise(key, cachePromise);
    }

    // 使用 ! 非空断言
    return () => cachePromise!;
  }

  ....
}

建议项目内部维护唯一单例

使用方式

小程序

建议在 app.ts 中的 globalData 里面,初始化队列:

import AsyncQueue from '@retailwe/common-libs-async-queue';

App({
  globalData: {
    asyncQueue: new AsyncQueue()
  }
});

业务层请求缓存封装

// service 使用
const mockService = async (key: string): Promise<any> => {
  const testPromise = queue.getPromise(key);
  if (testPromise) return testPromise;

  const tempPromise = asyncFn(key);
  queue.setPromise(key, tempPromise);
  const val = await tempPromise;
  return new Promise(resolve => resolve(val));
};

// 单元测试
test('asnycQueue test1', async t => {
  const key1 = 'asyncQueue1';
  const promiseAll = await Promise.all([mockService(key1), mockService(key1)]);
  t.is(queue.getQueue(key1)?.length, 0);
  t.is(JSON.stringify(promiseAll), JSON.stringify([1, 1]));
});

// 通过 cachePromise 直接缓存一个 () => Promise<any> 函数
test.serial('test cachePromise', async t => {
  const key = 'cachePromise';
  const fn1 = queue.cachePromise<number>(key, () => mockPromiseFn(1));
  t.is(queue.getQueue(key)?.length, 1);
  t.is(await fn1(), 1);
  const fn2 = queue.cachePromise<number>(key, () => mockPromiseFn(2));
  // 这里会使用上一次队列的缓存,所以第二次的结果是上一次的结果
  t.is(await fn2(), 1);
  // cache 相同 key, 队列数不变,
  t.is(queue.getQueue(key)?.length, 0);
  // 队列 map.size + 1
  t.is(queue.getQueues().size, 3);
});