Fix error handling when refreshing
This commit is contained in:
		
							parent
							
								
									43160d153e
								
							
						
					
					
						commit
						7e3e928682
					
				
					 1 changed files with 30 additions and 16 deletions
				
			
		| 
						 | 
				
			
			@ -193,21 +193,35 @@ function onTrainData(data) {
 | 
			
		|||
 | 
			
		||||
var refreshStopToken = null
 | 
			
		||||
function refresh() {
 | 
			
		||||
	return fetch(`https://scraper.infotren.dcdev.ro/v2/train/${trainNumber}?date=${date.getFullYear().toString()}-${(date.getMonth() + 1).toString().padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`)
 | 
			
		||||
		.then(function (response) {
 | 
			
		||||
			return response.json()
 | 
			
		||||
		})
 | 
			
		||||
		.then(function (response) {
 | 
			
		||||
			trainData = response
 | 
			
		||||
			onTrainData(response)
 | 
			
		||||
		})
 | 
			
		||||
		.then(function () {
 | 
			
		||||
	function reschedule(timeout) {
 | 
			
		||||
		if (refreshStopToken != null) {
 | 
			
		||||
			clearTimeout(refreshStopToken)
 | 
			
		||||
		}
 | 
			
		||||
		refreshStopToken = setTimeout(function () { 
 | 
			
		||||
			refresh()
 | 
			
		||||
			}, 60000)
 | 
			
		||||
		}, timeout || 60000)
 | 
			
		||||
	}
 | 
			
		||||
	return fetch(
 | 
			
		||||
		`https://scraper.infotren.dcdev.ro/v2/train/${trainNumber}?date=${date.getFullYear().toString()}-${(date.getMonth() + 1).toString().padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`,
 | 
			
		||||
		{
 | 
			
		||||
			cache: 'no-store',
 | 
			
		||||
		},
 | 
			
		||||
	).then(function (response) {
 | 
			
		||||
		if (!response.ok) {
 | 
			
		||||
			// Check in 10 seconds if server returned error
 | 
			
		||||
			reschedule(10000)
 | 
			
		||||
			return
 | 
			
		||||
		}
 | 
			
		||||
		return response.json()
 | 
			
		||||
	}).then(function (response) {
 | 
			
		||||
		trainData = response
 | 
			
		||||
		onTrainData(response)
 | 
			
		||||
	}).then(function () {
 | 
			
		||||
		reschedule()
 | 
			
		||||
	}).catch(function (e) {
 | 
			
		||||
		// Check in 1 second if network error
 | 
			
		||||
		reschedule(1000)
 | 
			
		||||
		throw e
 | 
			
		||||
	})
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
| 
						 | 
				
			
			
 | 
			
		|||
		Loading…
	
	Add table
		
		Reference in a new issue