Add robustness to download script

This commit is contained in:
pietervdvn 2021-05-14 17:37:21 +02:00
parent 7101baf13b
commit 703b66195f

View file

@ -18,10 +18,13 @@ export default class ScriptUtils {
return result; return result;
} }
public static DownloadJSON(url) : Promise<any>{ public static DownloadJSON(url): Promise<any> {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
try {
https.get(url, (res) => { https.get(url, (res) => {
const parts : string[] = [] const parts: string[] = []
res.setEncoding('utf8'); res.setEncoding('utf8');
res.on('data', function (chunk) { res.on('data', function (chunk) {
// @ts-ignore // @ts-ignore
@ -30,24 +33,27 @@ export default class ScriptUtils {
res.addListener('end', function () { res.addListener('end', function () {
const result = parts.join("") const result = parts.join("")
try{ try {
resolve(JSON.parse(result)) resolve(JSON.parse(result))
}catch (e){ } catch (e) {
reject(e) reject(e)
} }
}); });
}) })
} catch (e) {
reject(e)
}
}) })
} }
public static sleep(ms) { public static sleep(ms) {
if(ms <= 0){ if (ms <= 0) {
process.stdout.write("\r \r") process.stdout.write("\r \r")
return; return;
} }
return new Promise((resolve) => { return new Promise((resolve) => {
process.stdout.write("\r Sleeping for "+(ms/1000)+"s \r") process.stdout.write("\r Sleeping for " + (ms / 1000) + "s \r")
setTimeout(resolve, 1000); setTimeout(resolve, 1000);
}).then(() => ScriptUtils.sleep(ms - 1000)); }).then(() => ScriptUtils.sleep(ms - 1000));
} }