在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
}
},