27
loading...
This website collects cookies to deliver better user experience
class Configuration {
static _configuration = {};
static loadConfiguration() {
// do something
}
static saveConfiguration(newConfig) {
// do another thing
}
}
const xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = myLoadFunction;
xhr.onerror = myErrorFunction;
xhr.send();
fetch(method, url)
.then((response) => { // do something with the response })
.catch((reason) => { // do something with the reason});
try {
await fetch(method, url);
// do something with the response
} catch (reason) {
// do something with the reason
}
class GameHandler {
async initializeGame(params) {
const response = await fetch(
"example.com/rest/api/startGame",
{ body: JSON.stringify(params), method: "POST" }
);
const obj = await response.json();
this.myGameId = obj.gameId;
}
async updateGame(progress, finished) {
const params = { id: this.myGameId, progress: progress, finished: finished };
const response = await fetch(
"example.com/rest/api/updateGame",
{ body: JSON.stringify(params), method: "POST" }
);
const obj = await response.json();
if (finished) {
this.myScore = obj.score;
}
}
}
class GameHandler {
static startGamePromise;
async static initializeGame(params) {
if (GameHandler.startGamePromise) {
// the game already started
return GameHandler.startGamePromise;
}
// Create a promise and save it on a static variable
GameHandler.startGamePromise =
new Promise((resolve, reject) => async {
try {
GameHandler.myGameId = await GameHandler.callStart(params);
resolve();
}
catch (e) {
reject(e);
}
});
}
async updateGame(progress, finished) {
if (!GameHandler.startGamePromise) {
throw new Error("Game didn't start");
}
// Make sure that the game has been initialized
await GameHandler.startGamePromise;
// Call the update game API
const = await GameHandler.callUpdate(progress, finished);
if (finished) {
this.myScore = obj.score;
}
}
(...)
await GameHandler.startGamePromise;