-
Notifications
You must be signed in to change notification settings - Fork 0
/
promiseMethods.js
112 lines (97 loc) · 2.72 KB
/
promiseMethods.js
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/*
without calling Promise.race(), Promise.any(), Promise.all(), Promise.allSettled(), implement the following four similar functions on the
native Promise object:
myrace(promises): Takes in an array of promises and returns a new Promise. This new promise should resolve or reject as soon as any promise
in the array rsolves or rejects, with the value from that serttled promise.
*/
Promise.myRace = function (promises) {
return new Promise((resolve,reject) => {
promises.forEach(promise => {
promise.then(resolve).catch(reject);
})
})
};
export default function promiseRace(iterable) {
return new Promise((resolve,reject) => {
if(iterable.length === 0) {
return;
}
iterable.forEach(async (item) => {
try {
const value = await item;
resolve(value);
} catch (err) {
reject(err);
}
})
})
}
Promise.myAny = function (promises) {
return new Promise((resolve,reject) => {
let rejectCount = 0;
promises.forEach(promise => {
promise.then(resolve).catch(_ => {
rejectCount++;
if(rejectCount === promises.length) {
reject('all promises rejected');
}
});
})
})
};
Promise.myAll = function (promises) {
return new Promise((resolve,reject) => {
const results = [];
let resolvedCount = 0;
promises.forEach((promise,i) => {
promise.then(value => {
results[i] = value;
resolvedCount++;
if(resolvedCount === promises.length) {
resolve(results);
}
}).catch(reject);
})
})
};
export default function promiseAll(iterable) {
return new Promise((resolve,reject) => {
const results = [];
let resolvedCount = 0;
if(iterable.length === 0) {
resolve(results)
return;
}
iterable.forEach(async (promise,i) => {
try {
const value = await promise;
results[i] = value;
resolvedCount++;
if(resolvedCount === iterable.length) {
resolve(results);
}
}
catch(err) {
reject(err)
};
})
})
}
Promise.myAllSettled = function (promises) {
return new Promise((resolve,reject) => {
const results = [];
let settledCount = 0;
promises.forEach((promise,i) => {
promise.then(value => {
results[i] = {status: 'fulfilled', value}
}).catch(error => {
results[i] = {status: 'rejected', error}
}).finally(() => {
settledCount++;
if(settledCount === promises.length) {
resolve(results);
}
})
})
})
};