Repositorio del curso CCOM4030 el semestre B91 del proyecto Artesanías con el Instituto de Cultura

retry.js 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #!/usr/bin/env node
  2. /*
  3. Licensed to the Apache Software Foundation (ASF) under one
  4. or more contributor license agreements. See the NOTICE file
  5. distributed with this work for additional information
  6. regarding copyright ownership. The ASF licenses this file
  7. to you under the Apache License, Version 2.0 (the
  8. "License"); you may not use this file except in compliance
  9. with the License. You may obtain a copy of the License at
  10. http://www.apache.org/licenses/LICENSE-2.0
  11. Unless required by applicable law or agreed to in writing,
  12. software distributed under the License is distributed on an
  13. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. KIND, either express or implied. See the License for the
  15. specific language governing permissions and limitations
  16. under the License.
  17. */
  18. 'use strict';
  19. var events = require('cordova-common').events;
  20. /*
  21. * Retry a promise-returning function a number of times, propagating its
  22. * results on success or throwing its error on a failed final attempt.
  23. *
  24. * @arg {Number} attemptsLeft - The number of times to retry the passed call.
  25. * @arg {Function} promiseFunction - A function that returns a promise.
  26. * @arg {...} - Arguments to pass to promiseFunction.
  27. *
  28. * @returns {Promise}
  29. */
  30. module.exports.retryPromise = function (attemptsLeft, promiseFunction) {
  31. // NOTE:
  32. // get all trailing arguments, by skipping the first two (attemptsLeft and
  33. // promiseFunction) because they shouldn't get passed to promiseFunction
  34. var promiseFunctionArguments = Array.prototype.slice.call(arguments, 2);
  35. return promiseFunction.apply(undefined, promiseFunctionArguments).then(
  36. // on success pass results through
  37. function onFulfilled (value) {
  38. return value;
  39. },
  40. // on rejection either retry, or throw the error
  41. function onRejected (error) {
  42. attemptsLeft -= 1;
  43. if (attemptsLeft < 1) {
  44. throw error;
  45. }
  46. events.emit('verbose', 'A retried call failed. Retrying ' + attemptsLeft + ' more time(s).');
  47. // retry call self again with the same arguments, except attemptsLeft is now lower
  48. var fullArguments = [attemptsLeft, promiseFunction].concat(promiseFunctionArguments);
  49. return module.exports.retryPromise.apply(undefined, fullArguments);
  50. }
  51. );
  52. };