|
| 1 | +// * Basic promise example |
| 2 | +const myPromise = new Promise((res, rej) => res('Promise Resolved')) |
| 3 | + |
| 4 | +// ;(async () => { |
| 5 | +// try { |
| 6 | +// const res = await myPromise |
| 7 | +// console.log({ res }) |
| 8 | +// } catch (error) { |
| 9 | +// console.log(error) |
| 10 | +// } |
| 11 | +// })() |
| 12 | + |
| 13 | +// * Delay/Sleep function |
| 14 | +const sleep = delay => |
| 15 | + new Promise((res, rej) => setTimeout(() => res('Ran after sleep..'), delay)) |
| 16 | + |
| 17 | +// ;(async () => { |
| 18 | +// try { |
| 19 | +// const res = await sleep(2000) |
| 20 | +// console.log('🚀 ~res:', res) |
| 21 | +// } catch (error) {} |
| 22 | +// })() |
| 23 | + |
| 24 | +/* |
| 25 | +* Promise.all: |
| 26 | +* Promise.all: |
| 27 | +* 1. If any of the input promises is rejected, the entire returned promise will immediately reject with the reason of the first rejected promise. |
| 28 | +* 2. Resolves only if all input promises are resolved successfully. The resolved value is an array containing the resolved values of the input promises in the same order. |
| 29 | +* use case: Useful when you want to wait for multiple asynchronous operations to complete and need all of them to be successful before proceeding. For example, making multiple API requests in parallel and waiting for all responses. |
| 30 | +
|
| 31 | +* Promise.allSettled: |
| 32 | +* 1. The returned promise always resolves, regardless of whether individual promises were fulfilled or rejected. |
| 33 | +* 2. Resolves with an array of objects, one for each input promise. These objects contain the status of each promise ("fulfilled" or "rejected") along with the value (if resolved) or reason (if rejected). |
| 34 | +* use case: Useful when you want to gather the results of multiple asynchronous operations, regardless of whether they succeeded or failed. It's often used when you want to know the outcome of all promises, even if some of them are rejected. |
| 35 | +
|
| 36 | +* Promise.race: |
| 37 | +* As the name suggests, race returns first promise with shortest delay whether it is resolved or rejected. |
| 38 | +* use case: This can be useful when you're interested in the result of the first promise to complete, regardless of whether it's a success or failure. |
| 39 | +* resolution: Resolves as soon as the first promise in the input array settles, whether it's resolved or rejected. The returned promise adopts the outcome (either resolve or reject) of the first settled promise |
| 40 | +* use case: useful when you want to implement scenarios like a timeout mechanism where you want to respond to the first promise to complete, regardless of whether it succeeds or fails. |
| 41 | +
|
| 42 | +* Promise.any(): |
| 43 | +* It will return with first resolved promise. |
| 44 | +* resolution: Resolves as soon as any one of the input promises resolves. It doesn't matter if the other promises reject. The returned promise adopts the resolved value of the first resolved promise. |
| 45 | +* use case: Useful when you want to handle the case where at least one promise out of multiple promises succeeds, and you're interested in the result of the first resolving promise |
| 46 | +*/ |
| 47 | + |
| 48 | +// * Promise All |
| 49 | +// const p1 = new Promise((res, rej) => res(1)) |
| 50 | +// const p3 = new Promise(res => setTimeout(() => res('Delayed promise'), 3000)) |
| 51 | +// const p2 = new Promise((res, rej) => res(2)) |
| 52 | +// const p4 = new Promise((res, rej) => setTimeout(() => rej('Rejected'), 500)) |
| 53 | + |
| 54 | +// * Promise.all |
| 55 | +// ;(async () => { |
| 56 | +// try { |
| 57 | +// const res = await Promise.all([p1, p2, p3, p4]) |
| 58 | +// console.log('🚀 ~ ; ~ res:', res) |
| 59 | +// } catch (error) { |
| 60 | +// console.log('🚀 ~ ; ~ error:', error) |
| 61 | +// } |
| 62 | +// })() |
| 63 | + |
| 64 | +// * Promise.allSettled |
| 65 | +// ;(async () => { |
| 66 | +// try { |
| 67 | +// const res = await Promise.allSettled([p1, p2, p3, p4]) |
| 68 | +// console.log('🚀 ~ ; ~ res:', res) |
| 69 | +// } catch (error) { |
| 70 | +// console.log({ error }) |
| 71 | +// } |
| 72 | +// })() |
| 73 | + |
| 74 | +/** |
| 75 | + { res: 'Promise Resolved' } |
| 76 | +🚀 ~ ; ~ res: [ |
| 77 | + { status: 'fulfilled', value: 1 }, |
| 78 | + { status: 'fulfilled', value: 2 }, |
| 79 | + { status: 'fulfilled', value: 'Delayed promise' }, |
| 80 | + { status: 'rejected', reason: 'Rej' } |
| 81 | +] |
| 82 | + */ |
| 83 | + |
| 84 | +// * Promise.race |
| 85 | +// ;(async () => { |
| 86 | +// try { |
| 87 | +// const res = await Promise.race([p1, p2, p3, p4]) |
| 88 | +// console.log('🚀 ~ ; ~ res:', res) |
| 89 | +// } catch (error) { |
| 90 | +// console.log({ error }) |
| 91 | +// } |
| 92 | +// })() |
| 93 | + |
| 94 | +// * Promise.any |
| 95 | +// ;(async () => { |
| 96 | +// try { |
| 97 | +// const res = await Promise.any([p1, p2, p3, p4]) |
| 98 | +// console.log('🚀 ~ ; ~ res:', res) |
| 99 | +// } catch (error) { |
| 100 | +// console.log({ error }) |
| 101 | +// } |
| 102 | +// })() |
| 103 | + |
| 104 | +// * -------------------- Polyfills -------------------- |
| 105 | + |
| 106 | +const p1 = new Promise((res, rej) => res(1)) |
| 107 | +const p3 = new Promise(res => setTimeout(() => res('Delayed promise'), 3000)) |
| 108 | +const p2 = new Promise((res, rej) => res(2)) |
| 109 | +const p4 = new Promise((res, rej) => setTimeout(() => res('Resolved'), 500)) |
| 110 | +const p5 = new Promise((res, rej) => setTimeout(() => rej('Rejected!!!'), 600)) |
| 111 | + |
| 112 | +// const resolvedPromises = [p1, p2, p3, p4] |
| 113 | +const rejectedPromises = [p1, p2, p3, p4, p5] |
| 114 | + |
| 115 | +const myPromiseAll = function (promises) { |
| 116 | + let result = [] |
| 117 | + let total = 0 |
| 118 | + const promise = new Promise(function (resolve, reject) { |
| 119 | + promises.forEach((item, index) => { |
| 120 | + Promise.resolve(item) |
| 121 | + .then(res => { |
| 122 | + result[index] = res |
| 123 | + total++ |
| 124 | + if (total === promises.length) resolve(result) |
| 125 | + }) |
| 126 | + .catch(err => { |
| 127 | + reject(err) |
| 128 | + }) |
| 129 | + }) |
| 130 | + }) |
| 131 | + return promise |
| 132 | +} |
| 133 | + |
| 134 | +const myPromiseAllFunction = promises => { |
| 135 | + let results = [] |
| 136 | + let completed = 0 |
| 137 | + |
| 138 | + // Create new promise |
| 139 | + const finalPromise = new Promise((resolve, reject) => { |
| 140 | + // * Loop over promises |
| 141 | + promises.forEach((item, index) => { |
| 142 | + // * resolve each promise |
| 143 | + Promise.resolve(item) |
| 144 | + .then(res => { |
| 145 | + //* if resolved add the result in results array |
| 146 | + results[index] = res |
| 147 | + completed++ |
| 148 | + // * when end is reached resolve the promise |
| 149 | + if (completed === promises.length) resolve(results) |
| 150 | + }) |
| 151 | + .catch(e => reject(e)) |
| 152 | + }) |
| 153 | + }) |
| 154 | + // * return the final promise |
| 155 | + return finalPromise |
| 156 | +} |
| 157 | + |
| 158 | +const myPromiseAllSettled = promises => { |
| 159 | + // const mappedPromises = promises.map(Promise.resolve(p).then(res =>{})) |
| 160 | + const mappedPromises = promises.map(p => |
| 161 | + Promise.resolve(p) |
| 162 | + .then(value => ({ |
| 163 | + status: 'fullfilled', |
| 164 | + value, |
| 165 | + })) |
| 166 | + .catch(e => ({ |
| 167 | + status: 'rejected', |
| 168 | + reason: e, |
| 169 | + })) |
| 170 | + ) |
| 171 | + return Promise.all(mappedPromises) |
| 172 | +} |
| 173 | + |
| 174 | +;(async () => { |
| 175 | + try { |
| 176 | + const res = await myPromiseAllFunction(rejectedPromises) |
| 177 | + console.log('🚀 ~ ; ~ res:', res) |
| 178 | + } catch (error) { |
| 179 | + console.log(error) |
| 180 | + } |
| 181 | +})() |
0 commit comments