async/await 与 Promises.all 并行获取

fetch in parallel async/await with Promises.all

我继续与 serial/parallel 在 JS 中处理(承诺)作斗争。我想查询我的服务器并识别那些花费时间超过 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
    }
  },

当 运行 并行查询时,您必须添加代码(类似于您在 non-parallel 示例中使用的代码)来分别为每个查询计时,以便您可以分别跟踪每个单独的请求.

每个请求的时间重叠,因此您无法从外部跟踪每个单独请求的时间。以下是对每个单独请求进行计时的示例:

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;
};

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