|
| 1 | +/** |
| 2 | + * Retries a given function multiple times with a delay between each attempt. |
| 3 | + * |
| 4 | + * @param {Function} func - The function to be executed and potentially retried on failure. |
| 5 | + * @param {number} retries - The number of times to retry the function if it fails or returns a null/undefined result. |
| 6 | + * @param {number} delayTime - The delay time between retries, in milliseconds. |
| 7 | + * |
| 8 | + * @returns {any} - Returns the result of the function if successful within the allowed retries; |
| 9 | + * otherwise, returns the last result (which may be null or undefined). |
| 10 | + * |
| 11 | + * The function attempts to execute the provided `func()` and checks for a non-null result. If the result is null |
| 12 | + * or an exception occurs, it retries the function up to the specified `retries`, with a delay of `delayTime` |
| 13 | + * milliseconds between each attempt. |
| 14 | + * |
| 15 | + * Example usage: |
| 16 | + * |
| 17 | + * function getToken() { |
| 18 | + * // Simulated operation that might fail |
| 19 | + * var request = new sn_ws.RESTMessageV2("token", "GET"); |
| 20 | + * var response = request.execute(); |
| 21 | + * var statusCode = response.getStatusCode(); |
| 22 | + * var result = null; |
| 23 | + * switch(statusCode) { |
| 24 | + * case 200: |
| 25 | + * result = JSON.parse(response.getBody()); |
| 26 | + * break; |
| 27 | + * default: |
| 28 | + * throw new Error("request failed, http status code: " + statusCode); |
| 29 | + * } |
| 30 | + * return result; |
| 31 | + * } |
| 32 | + * |
| 33 | + * var result = retry(getToken, 3, 2000); // Try 3 times, with a 2-second delay between each attempt |
| 34 | + * gs.info("Operation result: " + result); |
| 35 | + */ |
| 36 | +function retry(func, retires, delayTime) { |
| 37 | + var result = null; |
| 38 | + for(var i = 0; i < retires; i++) { |
| 39 | + try { |
| 40 | + result = func(); |
| 41 | + //error handling could depending on the implementation of func |
| 42 | + if(!gs.nil(result)) return result; |
| 43 | + } catch (error) { |
| 44 | + gs.error(error); |
| 45 | + } |
| 46 | + gs.sleep(delayTime); |
| 47 | + } |
| 48 | + return result; |
| 49 | +} |
| 50 | + |
| 51 | + |
0 commit comments