美文网首页
前端队列收集编码,一次请求,分别返回结果给来源

前端队列收集编码,一次请求,分别返回结果给来源

作者: 晓蟲QwQ | 来源:发表于2024-06-27 14:07 被阅读0次

最近做了个需求,后端返回商品信息给前端,但是信息中缺少图片地址,需要通过额外的接口获取。因为一个列表会展示多个商品,为了减少请求,需要收集页面展示商品的编码,在一定的时间后使用一个接口一次获取回来,并返回给各个请求来源。

class ImageManager {
  private imageCache = new Map<string, string>();
  private pendingRequests: { code: string; resolve: (url: string) => void; reject: (error: Error) => void }[] = [];
  private batchTimer: number | null = null; // 修改为适合浏览器环境的类型标注
  private readonly batchInterval = 500; // 批量请求的时间间隔,单位为毫秒

  /**
   * 异步获取图片URL
   * @param {string} code - 图片code
   * @returns {Promise<string>} 图片URL的Promise
   */
  async getImageUrl(code: string): Promise<string> {
    return new Promise((resolve, reject) => {
      if (this.imageCache.has(code)) {
        resolve(this.imageCache.get(code)!);
      } else {
        this.pendingRequests.push({ code, resolve, reject });
        if (!this.batchTimer) {
          this.batchTimer = window.setTimeout(() => this._processPendingRequests(), this.batchInterval); // 明确使用window对象
        }
      }
    });
  }

  /**
   * 处理待处理的图片请求
   */
  private async _processPendingRequests() {
    if (this.batchTimer) {
      window.clearTimeout(this.batchTimer); // 明确使用window对象
    }
    this.batchTimer = null;

    try {
      const uniqueCodes = Array.from(new Set(this.pendingRequests.map(req => req.code)));
      const fetchedImages = await this._batchFetch(uniqueCodes);

      fetchedImages.forEach((url, code) => {
        this.imageCache.set(code, url);
        const request = this.pendingRequests.find(req => req.code === code);
        if (request) {
          request.resolve(url);
        }
      });

      this.pendingRequests = [];
    } catch (error) {
      this.pendingRequests.forEach(req => req.reject(error));
      this.pendingRequests = [];
      console.error('Failed to fetch images batch:', error);
    }
  }

  /**
   * 模拟批量获取图片URL的网络请求
   * @param {Array<string>} codes - 需要获取的图片code数组
   * @returns {Promise<Map<string, string>>} 返回一个映射,键为图片code,值为图片URL
   */
  private async _batchFetch(codes: string[]): Promise<Map<string, string>> {
    // 实际应用中,这里应该替换为真实的API调用
    const mockResponse = new Map(codes.map(code => [code, `https://example.com/images/${code}.jpg`]));
    return new Promise(resolve => setTimeout(() => resolve(mockResponse), 1000)); // 模拟延迟
  }
}

export const imageManager = new ImageManager();

相关文章

  • Servlet-中文乱码

    前端-提交前处理中文乱码 服务端-对提交的请求编码和解码 服务端-将返回的数据编码和解码

  • Angular---添加一个loading组件

    我们向服务端发起请求时,从前端发出请求到后端将响应结果返回给前端,这期间有一个空白的等待期,无论它是1毫秒、10秒...

  • GCD多个请求有序执行

    只使用GCD队列组只能实现相应请求的有序执行,并不能保证请求结果的有序返回 通过信号量加锁实现网络请求结果的有序返...

  • thinkphp处理前端跨域请求

    1、前端js正常ajax请求 后端php返回 2、前端js用ajax跨域请求 thinkphp返回 ajaxRet...

  • get请求返回结果为204

    问题描述:js端一个经过编码的get请求地址,返回给ios端,ios端请求一直返回204(空内容),而androi...

  • 前端请求返回

    200 – 服务器成功返回网页404 – 请求的网页不存在503 – 服务器超时500(服务器内部错误) 服务器遇...

  • swoole笔记03(搭建http服务器)

    常规: http请求从nginx->fast-cgi->php->返回给前端用户 (fpm) swoole ...

  • 力扣题解(队列)

    933. 最近的请求次数 构建一个请求队列,之前的请求与当前请求时间间隔大于 3000 ms 的出队列,最后返回队...

  • svg-captcha前后端使用

    前端请求获取验证码接口,后端生成返回给前端,同时存入session前端填写验证码,提交后和后端session里面存...

  • dispatch_group_notify、dispatch_g

    最近在编码一个多重网络请求,必须等所有请求结束才能最终返回结果,与此同时,请求涉及多次同步异步来回问题。经过不断的...

网友评论

      本文标题:前端队列收集编码,一次请求,分别返回结果给来源

      本文链接:https://www.haomeiwen.com/subject/tyqecjtx.html