* Polls a URL with GET requests until it returns a 2xx response or the * timeout expires. * @param {string} url The URL to poll. * @param {number} timeout How long to wait, in milliseconds. * @param {Promise=} opt_cancelToken A promise used as a cancellation signal: * if resolved before the
(url, timeout, opt_cancelToken)
| 110 | * the given URL, or if the wait is cancelled. |
| 111 | */ |
| 112 | function waitForUrl(url, timeout, opt_cancelToken) { |
| 113 | return new Promise((onResolve, onReject) => { |
| 114 | let client = new HttpClient(url) |
| 115 | let request = new HttpRequest('GET', '') |
| 116 | let start = Date.now() |
| 117 | |
| 118 | let done = false |
| 119 | let resolve = () => { |
| 120 | done = true |
| 121 | onResolve() |
| 122 | } |
| 123 | let reject = (err) => { |
| 124 | done = true |
| 125 | onReject(err) |
| 126 | } |
| 127 | |
| 128 | if (opt_cancelToken) { |
| 129 | opt_cancelToken.then((_) => reject(new CancellationError())) |
| 130 | } |
| 131 | |
| 132 | testUrl() |
| 133 | |
| 134 | function testUrl() { |
| 135 | client.send(request).then(onResponse, onError) |
| 136 | } |
| 137 | |
| 138 | function onError() { |
| 139 | if (Date.now() - start > timeout) { |
| 140 | reject(Error('Timed out waiting for the URL to return 2xx: ' + url)) |
| 141 | } else { |
| 142 | setTimeout(function () { |
| 143 | if (!done) { |
| 144 | testUrl() |
| 145 | } |
| 146 | }, 50) |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | function onResponse(response) { |
| 151 | if (done) { |
| 152 | return |
| 153 | } |
| 154 | if (response.status > 199 && response.status < 300) { |
| 155 | resolve() |
| 156 | return |
| 157 | } |
| 158 | onError() |
| 159 | } |
| 160 | }) |
| 161 | } |
| 162 | |
| 163 | // PUBLIC API |
| 164 | module.exports.getStatus = getStatus |