Advertisement
Guest User

Untitled

a guest
Feb 14th, 2016
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. checkAppPr: function (port) {
  2. var result = Promise.defer();
  3. var checkStatus = function (next, result, times) {
  4. portscanner.checkPortStatus(port, '127.0.0.1', function (error, status) {
  5. if (error) {
  6. result.reject(error);
  7. } else {
  8. if (status === 'open') {
  9. console.log("Application status: open");
  10. result.resolve();
  11. } else {
  12. times--;
  13. if (times > 0) {
  14. setTimeout(function () {
  15. next(next, result, times);
  16. }, 1000);
  17. } else {
  18. result.reject("start timeout");
  19. }
  20. }
  21. }
  22. })
  23. }
  24. checkStatus(checkStatus, result, 20);
  25. return result.promise;
  26. }
  27.  
  28. // Returns a promise that resolves when the port is open
  29. checkPortStatus: function(port, host){
  30. return new Promise((resolve, reject) => {
  31. portscanner.checkPortStatus(port, host, function(error, status) {
  32. if(error)
  33. reject(error);
  34. else if(status === 'open')
  35. resolve(status);
  36. else
  37. reject(new Error('Port is not open'));
  38. });
  39. });
  40. },
  41.  
  42. // Your API function
  43. checkAppPort: function(port, retriesLeft) {
  44.  
  45. const TIME_BETWEEN_CHECKS = 1000;
  46. const HOST = '127.0.0.1';
  47. const RETRIES = 20;
  48.  
  49. // Setting a default to retriesLeft
  50. retriesLeft = retriesLeft === void 0 ? RETRIES : retriesLeft;
  51.  
  52. if(!port) throw new Error('Port is required');
  53. if(retriesLeft === 0) return Promise.reject('Timed Out');
  54.  
  55. return new Promise((resolve, reject) => {
  56.  
  57. // We call our checker. When it resolves, it calls this promise's resolve.
  58. // If it rejects, we do added work.
  59. this.checkPortStatus(port, host).then(resolve, error => {
  60. setTimeout(() => {
  61.  
  62. // Call this function again, with one less retry. However, we hook our
  63. // resolve and reject to the promise of the new call effectively making
  64. // a chain when it keeps failing.
  65. this.checkAppPort(port, retriesLeft - 1).then(resolve, reject);
  66.  
  67. }, TIME_BETWEEN_CHECKS);
  68. });
  69. });
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement