From 779ba8a1b81049e02053d9bf0232bd6f24807acf Mon Sep 17 00:00:00 2001 From: Bjorn Stromberg Date: Sat, 15 Aug 2020 23:26:54 +0900 Subject: [PATCH] Using reject here is uncaught, make this a single promise and resolve/reject accordingly (#556) --- src/js/platform/browser/game_analytics.js | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/src/js/platform/browser/game_analytics.js b/src/js/platform/browser/game_analytics.js index 73da3696..7336ffd9 100644 --- a/src/js/platform/browser/game_analytics.js +++ b/src/js/platform/browser/game_analytics.js @@ -85,10 +85,9 @@ export class ShapezGameAnalytics extends GameAnalyticsInterface { * @returns {Promise} */ sendToApi(endpoint, data) { - return Promise.race([ - new Promise((resolve, reject) => { - setTimeout(() => reject("Request to " + endpoint + " timed out"), 20000); - }), + return new Promise((resolve, reject) => { + const timeout = setTimeout(() => reject("Request to " + endpoint + " timed out"), 20000); + fetch(analyticsUrl + endpoint, { method: "POST", mode: "cors", @@ -103,13 +102,19 @@ export class ShapezGameAnalytics extends GameAnalyticsInterface { body: JSON.stringify(data), }) .then(res => { + clearTimeout(timeout); if (!res.ok || res.status !== 200) { - throw new Error("Fetch error: Bad status " + res.status); + reject("Fetch error: Bad status " + res.status); + } else { + return res.json(); } - return res; }) - .then(res => res.json()), - ]); + .then(resolve) + .catch(reason => { + clearTimeout(timeout); + reject(reason); + }); + }); } /**