-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathasynchronous-recursion.ts
More file actions
65 lines (58 loc) · 1.44 KB
/
asynchronous-recursion.ts
File metadata and controls
65 lines (58 loc) · 1.44 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
interface ResultShape {
code: number;
end: boolean;
value: string;
}
const yelidSomeValueFn = (params: unknown, cb: (data: ResultShape) => void) => {
setTimeout(
() =>
cb({ code: 1, end: Math.random() > 0.5, value: "the value" + params }),
500
);
};
const getAllValue = (cb: (dataList: ResultShape[]) => void) => {
yelidSomeValueFn(1, (r) => {
if (r.end) {
cb([r]);
} else {
getAllValue((c) => cb(c.concat(r)));
}
});
};
const yelidSomeValueFnWithPromise = (params: number) =>
new Promise<ResultShape>((resolve) => {
setTimeout(
() =>
resolve({
code: 1,
end: Math.random() > 0.5,
value: "the value" + params,
}),
500
);
});
const getAllValueWithPromise: () => Promise<ResultShape[]> = () =>
yelidSomeValueFnWithPromise(1).then((r) => {
if (r.end) {
return [r];
} else {
return getAllValueWithPromise().then((c) => c.concat(r));
}
});
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const yelidSomeValueFnWithAsync = async (params: number) => {
await sleep(500);
return {
code: 1,
end: Math.random() > 0.5,
value: "the value" + params,
};
};
const getAllValueWithAsync: () => Promise<ResultShape[]> = async () => {
const r = await yelidSomeValueFnWithAsync(1);
if (r.end) {
return [r];
} else {
return (await getAllValueWithAsync()).concat(r);
}
};