-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathrpc.js
More file actions
40 lines (35 loc) · 987 Bytes
/
Copy pathrpc.js
File metadata and controls
40 lines (35 loc) · 987 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
function unary(client, method, request) {
return new Promise((resolve, reject) => {
client[method](request, (error, response) => {
if (error) reject(error);
else resolve(response);
});
});
}
async function* iterate(client, method, request) {
const stream = client[method](request);
const values = [];
let ended = false;
let failure;
stream.on("data", (value) => values.push(value));
stream.on("error", (error) => {
failure = error;
ended = true;
});
stream.on("end", () => {
ended = true;
});
while (!ended || values.length) {
if (failure) throw failure;
if (values.length) yield values.shift();
else await new Promise((resolve) => setImmediate(resolve));
}
if (failure) throw failure;
}
async function collect(client, method, request) {
const values = [];
for await (const value of iterate(client, method, request))
values.push(value);
return values;
}
module.exports = { collect, iterate, unary };