代码之家  ›  专栏  ›  技术社区  ›  punkish

并行异步获取/等待承诺。全部的

  •  0
  • punkish  · 技术社区  · 3 年前

    在JS(promises)中,我仍在努力进行串行/并行处理。我想查询我的服务器,并识别那些耗时超过500毫秒的查询。下面的方法很有效,但据我所知,查询是一个接一个地进行的。

    const query = async (queries) => {
        for (let i = 0, j = queries.length; i < j; i++) {
            let t = process.hrtime();
            const response = await fetch(queries[i]);
            const result = await response.json();
            t = process.hrtime(t);
            
            const ms = Math.round((t[0] * 1000) + (t[1] / 1000000));
            if (ms > 500) {
                console.log(ms, queries[i]);
            }
        }
    }
    
    query(arrayOfQueries);
    
    // console output below (snipped for brevity)
    3085 http://localhost:3010/v3/…
    2463 http://localhost:3010/v3/…
    2484 http://localhost:3010/v3/…
    …
    

    我更改了上面的代码,以并行启动查询,但现在我得到了一系列承诺。我不知道如何只识别那些需要500毫秒以上才能解决的承诺

    const query = async (queries) => {
        const r = await Promise.all(queries.map(async (q) => fetch(q)));
        console.log(r);
    };
    
    // console output
    [
      Response {
        size: 0,
        timeout: 0,
        [Symbol(Body internals)]: { body: [PassThrough], disturbed: false, error: null },
        [Symbol(Response internals)]: {
          url: 'http://localhost:3010/v3/…',
          status: 200,
          statusText: 'OK',
          headers: [Headers],
          counter: 0
        }
      },
      Response {
        size: 0,
        timeout: 0,
        [Symbol(Body internals)]: { body: [PassThrough], disturbed: false, error: null },
        [Symbol(Response internals)]: {
          url: 'http://localhost:3010/v3/…',
          status: 200,
          statusText: 'OK',
          headers: [Headers],
          counter: 0
        }
      },
      Response {
        size: 0,
        timeout: 0,
        [Symbol(Body internals)]: { body: [PassThrough], disturbed: false, error: null },
        [Symbol(Response internals)]: {
          url: 'http://localhost:3010/v3/…',
          status: 200,
          statusText: 'OK',
          headers: [Headers],
          counter: 0
        }
      },
    
    1 回复  |  直到 3 年前
        1
  •  1
  •   jfriend00    3 年前

    在并行运行查询时,必须添加代码(类似于非并行示例中的代码)来分别计时每个查询,以便可以分别跟踪每个请求。

    每个请求的时间重叠,因此您无法跟踪来自外部的每个单独请求的时间。下面是一个为每个请求计时的示例:

    const query = async (queries) => {
        const r = await Promise.all(queries.map(async (q) => {
            const start = Date.now();
            const response = await fetch(q);
            const json = await response.json();
            const delta = Date.now() - start;
            console.log(`${delta}ms for ${q}`);
            return json;
        });
        return r;
    };
    

    这将输出每个请求完成时的计时,其顺序可能与发出请求的顺序不同。如果需要,可以将这些计时结果收集到一个数组中,并在最后一次输出所有计时结果。

    推荐文章