|
| 1 | + |
| 2 | +/** |
| 3 | + * Immediately calls an asynchronous function and wraps its result into a promise that |
| 4 | + * can only be resolved, not rejected, regardless of the state of the promised returned |
| 5 | + * by the function. |
| 6 | + * |
| 7 | + * The returned promise will contain an object with the following fields: |
| 8 | + * |
| 9 | + * * `status`: A string, either "fulfilled" or "rejected", indicating the state of the |
| 10 | + * original promise. |
| 11 | + * * `value`: Only present if status is "fulfilled". The value that the promise was |
| 12 | + * fulfilled with. |
| 13 | + * * `reason`: Only present if status is "rejected". The reason that the promise was |
| 14 | + * rejected with. |
| 15 | + * |
| 16 | + * This object structure is similar to the one used by the [`Promise.allSettled()` |
| 17 | + * function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled). |
| 18 | + * |
| 19 | + * This function can be useful to make use of other functions in a fault-tolerant way. |
| 20 | + * |
| 21 | + * @param {Function} fct An asynchronous function |
| 22 | + * @returns {Promise<any>} A promise that will always be resolved with an object containing |
| 23 | + * a snapshot of the original promise state. |
| 24 | + * @example |
| 25 | + * import { snapshot, map, sleep } from 'modern-async' |
| 26 | + * |
| 27 | + * const array = [1, 2, 3] |
| 28 | + * |
| 29 | + * const result = await map(array, (v) => snapshot(async () => { |
| 30 | + * await sleep(10) // waits 10ms |
| 31 | + * if (v % 2 === 0) { // throws error on some values |
| 32 | + * throw Error("error") |
| 33 | + * } |
| 34 | + * return v |
| 35 | + * })) |
| 36 | + * |
| 37 | + * console.log(result) |
| 38 | + * // prints: |
| 39 | + * // [ |
| 40 | + * // { status: 'fulfilled', value: 1 }, |
| 41 | + * // { status: 'rejected', reason: Error: error }, |
| 42 | + * // { status: 'fulfilled', value: 3 } |
| 43 | + * // ] |
| 44 | + */ |
| 45 | +async function snapshot (fct) { |
| 46 | + try { |
| 47 | + const res = await fct() |
| 48 | + return { |
| 49 | + status: 'fulfilled', |
| 50 | + value: res |
| 51 | + } |
| 52 | + } catch (e) { |
| 53 | + return { |
| 54 | + status: 'rejected', |
| 55 | + reason: e |
| 56 | + } |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +export default snapshot |
0 commit comments