1 | import {isPromiseLike} from './helpers'
|
2 |
|
3 | export type NextFunction = (error?, ...args: any[]) => void;
|
4 |
|
5 | export function array<T>(array: T[] | ArrayLike<T>, body: (element: T, i: number, next: NextFunction) => void | PromiseLike<void>, complete: NextFunction)
|
6 | {
|
7 | var loop = function (i)
|
8 | {
|
9 | if (i == array.length)
|
10 | complete();
|
11 | else
|
12 | try
|
13 | {
|
14 | var promise=body(array[i], i, function (error?)
|
15 | {
|
16 | if (error)
|
17 | complete(error);
|
18 | else
|
19 | setImmediate(loop, i + 1)
|
20 | });
|
21 | if(promise && isPromiseLike(promise))
|
22 | {
|
23 | promise.then(()=>setImmediate(loop, i+1), complete);
|
24 | }
|
25 | }
|
26 | catch (e)
|
27 | {
|
28 | complete(e);
|
29 | }
|
30 | }
|
31 | loop(0);
|
32 | }
|
33 |
|
34 | export function object<T>(o: T, body: (element: T[keyof T], i: keyof T, next: NextFunction) => void, complete: NextFunction)
|
35 | {
|
36 | array(Object.keys(o) as (keyof T)[], function (key, i, next)
|
37 | {
|
38 | body(o[key], key, next);
|
39 | }, complete);
|
40 | }
|
41 |
|
42 | export function each<T>(array: T[] | ArrayLike<T>, body: (element: T, i?: number, next?: NextFunction) => PromiseLike<void>, complete: NextFunction): void
|
43 | export function each<T>(array: T[] | ArrayLike<T>, body: (element: T, i?: number, next?: NextFunction) => PromiseLike<void>): PromiseLike<void>
|
44 | export function each<T>(array: T[] | ArrayLike<T>, body: (element: T, i: number, next: NextFunction) => void, complete: NextFunction): void
|
45 | export function each(o: any, body: (element: any, i: string, next: NextFunction) => void, complete: NextFunction): void
|
46 | export function each<T>(array: T[] | ArrayLike<T>, body: (element: T, i: number, next: NextFunction) => void): PromiseLike<void>
|
47 | export function each(o: any, body: (element: any, i: string, next: NextFunction) => void): PromiseLike<void>
|
48 | export function each(it: any, body: (element: any, i: any, next: NextFunction) => void, complete?: NextFunction): void | PromiseLike<void>
|
49 | {
|
50 | if (complete)
|
51 | {
|
52 | if (Array.isArray(it) || typeof (it['length']) != 'undefined')
|
53 | return array(it, body, complete);
|
54 | return object(it, body, complete);
|
55 |
|
56 | }
|
57 | else
|
58 | {
|
59 | return new Promise((resolve, reject) =>
|
60 | {
|
61 | if (Array.isArray(it) || typeof (it['length']) != 'undefined')
|
62 | return array(it, body, function (err)
|
63 | {
|
64 | if (err)
|
65 | reject(err);
|
66 | else
|
67 | resolve();
|
68 | });
|
69 | return object(it, body, function (err)
|
70 | {
|
71 | if (err)
|
72 | reject(err);
|
73 | else
|
74 | resolve();
|
75 | });
|
76 | })
|
77 | }
|
78 | } |
\ | No newline at end of file |