I am new to using promises in javascript and I just cannot seem to get something that (I think) should be fairly basic working.
I am writing code for a turn-based game where during a player's turn, a number of things happen of which some are asynchronous (for example animations using setInterval
), while some are vanilla synchronous code. What I am trying to do is to determine when ALL of the functions required during a player's turn have completed, so that I can switch turns to the next player. The client side is pure HTML5/CSS/JS (using the canvas API for animation), while the back-end is PHP 8.1 and MySQL5.6 in case it matters.
The relevant functions of my current code look like this:
function performAction() {
// this is the function that is fired when the player presses a button to perform some action, for example "move 5 tiles"
// a few hundred lines of code to do stuff client-side like move validation etc.
drawPlayer(); // we now fire the client-side animation function so that players get instant feedback and don't need to wait for the server response in multi-player games
// if this is a multi-player online game, we now call a function to fetch data from the server, for example to check if this player is blocked from taking that move
if (gameType == "remoteHuman") {
sendAction(data);
}
// otherwise, we don't need to contact the server if the player is playing a local AI game and can continue with the remaining actions
else {
completeAction(data);
}
}
function completeAction(data) {
// this function carries out the remaining tasks required on the client based on either the server response, or being called directly from performAction in local, single-player games
updateStats(); // update all the player's stats
textOverlay(); // draw a nice, floaty text overlay that shows some numbers and fades out
}
function updateStats() {
// this function is maybe a hundred lines of standard, synchronous code that updates player statistics like health etc.
// we are at the bottom of the code, so the updateStats function has now completed at this point since it's synchronous
}
function drawPlayer() {
// this function is the main animation function and is called towards the end of function performAction so that the player gets nice, instant response to actions without waiting for server responses etc.
function animate() {
// this is the core animation function that performs the canvas API drawing for each frame of an animation
// if we have finished drawing all the animation frames, then we are OK to clear the timer
if (currentFrame == frames.length) {
clearInterval(timer);
// the drawPlayer function has now completed at this point
}
}
// set up the locally scoped timer to run the animation function every frameDelay (about 20ms) for smooth animations
var timer = setInterval(function() {
animate();
}, frameDelay);
}
function textOverlay() {
// this function is a canvas drawing function that draws nice floaty text that fades out
// about a hundred lines of bog standard canvas api code here
// the actual, asynch drawing code. we delay the text overlay by about 500ms to better synchronise with animation actions first
setTimeout(function(){
// then we draw something and slowly reduce the opacity every frameDelay (about 20ms) until the text fades out
var interval = setInterval(function() {
// when our alpha is below zero, we know the text isn't on the screen anymore
if (alpha < 0) {
clearInterval(interval);
// the textOverlay function has now completed at this point
}
}, frameDelay);
}, animationDelay);
}
function sendAction(data) {
// this function is called from performAction whenever an event needs to be sent to the server in a multiplayer game. bog standard stuff. nothing to see here, move along
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var data = JSON.parse(xhttp.responseText);
completeAction(data);
}
xhttp.open("GET", serverURL "?data=" data);
xhttp.send();
}
I should note that all the above code works perfectly. What I need to know is when the functions drawPlayer, textOverlay, and updateStats have ALL completed, without chaining them in promises since I want them to all run asynchronously. I am only interested in when ALL of the functions have completed. The functions can never fail, so there is no need for error catching or failed response checking. Some stats about the functions:
- drawPlayer: has an asynch component mainly based on setInterval. takes anywhere between 200-1000ms to complete on a typical client, depending on the player action taken
- textOverlay: has an asynch component mainly based on setInterval. takes anywhere between 100-500ms to complete on a typical client
- updateStats: purely synchronous code. takes maybe 2-5ms to complete on a typical client. however, it is essential that this function has completed before the turn passes to the other player, so I need it included in the promise "chain" even though it is synchronous with low execution time compared to the drawing/animation functions
This is what I have tried so far:
- Instantiate a promise in performAction just before the call to drawPlayer(). Then at each point in the 3 dependent function when I know for sure that the functions have completed, I add a "then". Code below:
// set up as a global variable so that it can be accessed within any function in my code
var promiseA = new Promise(function(resolve) {
resolve(value);
console.log("promiseA created", value);
});
function performAction() {
// this is the function that is fired when the player presses a button to perform some action, for example "move 5 tiles"
// a few hundred lines of code to do stuff client-side like move validation etc.
drawPlayer(); // we now fire the client-side animation function so that players get instant feedback and don't need to wait for the server response in multi-player games
// if this is a multi-player online game, we now call a function to fetch data from the server, for example to check if this player is blocked from taking that move
if (gameType == "remoteHuman") {
sendAction(data);
}
// otherwise, we don't need to contact the server if the player is playing a local AI game and can continue with the remaining actions
else {
completeAction(data);
}
}
function completeAction(data) {
// this function carries out the remaining tasks required on the client based on either the server response, or being called directly from performAction in local, single-player games
updateStats(); // update all the player's stats
textOverlay(); // draw a nice, floaty text overlay that shows some numbers and fades out
}
function updateStats() {
// this function is maybe a hundred lines of standard, synchronous code that updates player statistics like health etc.
// we are at the bottom of the code, so the updateStats function has now completed at this point since it's synchronous
gv.promiseA.then(
function resolve(value) {
console.log("this function has completed", Date.now() - value);
}
);
}
function drawPlayer() {
// this function is the main animation function and is called towards the end of function performAction so that the player gets nice, instant response to actions without waiting for server responses etc.
function animate() {
// this is the core animation function that performs the canvas API drawing for each frame of an animation
// if we have finished drawing all the animation frames, then we are OK to clear the timer
if (currentFrame == frames.length) {
clearInterval(timer);
// the drawPlayer function has now completed at this point
gv.promiseA.then(
function resolve(value) {
console.log("this function has completed", Date.now() - value);
}
);
}
}
// set up the locally scoped timer to run the animation function every frameDelay (about 20ms) for smooth animations
var timer = setInterval(function() {
animate();
}, frameDelay);
}
function textOverlay() {
// this function is a canvas drawing function that draws nice floaty text that fades out
// about a hundred lines of bog standard canvas api code here
// the actual, asynch drawing code. we delay the text overlay by about 500ms to better synchronise with animation actions first
setTimeout(function(){
// then we draw something and slowly reduce the opacity every frameDelay (about 20ms) until the text fades out
var interval = setInterval(function() {
// when our alpha is below zero, we know the text isn't on the screen anymore
if (alpha < 0) {
clearInterval(interval);
// the textOverlay function has now completed at this point
gv.promiseA.then(
function resolve(value) {
console.log("this function has completed", Date.now() - value);
}
);
}
}, frameDelay);
}, animationDelay);
}
function sendAction(data) {
// this function is called from performAction whenever an event needs to be sent to the server in a multiplayer game. bog standard stuff. nothing to see here, move along
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var data = JSON.parse(xhttp.responseText);
completeAction(data);
}
xhttp.open("GET", serverURL "?data=" data);
xhttp.send();
}
However, this doesn't work because it just tells me when each "then" has completed, and not necessarily when all the "thens" have completed because I don't think this is proper chaining. But also, I don't want the functions to be truly "chained" since they need to all to start and run asynchronously as none of the functions are dependent on the results of the other functions, and anyway making them run in series would just slow things down for no reason.
- I've also tried instantiating 3 different promises (promiseA, promiseB, promiseC) at each point in the dependent code when I know the asynch functions will have completed. I then use an "all settled" check at the end of function completeAction():
// set up three global variables so that they can be accessed within any function in my code
var promiseA, promiseB, promiseC;
function performAction() {
// this is the function that is fired when the player presses a button to perform some action, for example "move 5 tiles"
// a few hundred lines of code to do stuff client-side like move validation etc.
drawPlayer(); // we now fire the client-side animation function so that players get instant feedback and don't need to wait for the server response in multi-player games
// if this is a multi-player online game, we now call a function to fetch data from the server, for example to check if this player is blocked from taking that move
if (gameType == "remoteHuman") {
sendAction(data);
}
// otherwise, we don't need to contact the server if the player is playing a local AI game and can continue with the remaining actions
else {
completeAction(data);
}
}
function completeAction(data) {
// this function carries out the remaining tasks required on the client based on either the server response, or being called directly from performAction in local, single-player games
updateStats(); // update all the player's stats
textOverlay(); // draw a nice, floaty text overlay that shows some numbers and fades out
// check if all three promises have been resolved before running a function to hand over play to the next player
Promise.allSettled([promiseA, promiseB, promiseC]).then(([result]) => {
var value = Date.now();
console.log("all functions completed", value);
console.log(result);
console.log("play can now be handed over to the other play");
nextPlayerTurn();
});
}
function updateStats() {
// this function is maybe a hundred lines of standard, synchronous code that updates player statistics like health etc.
// we are at the bottom of the code, so the updateStats function has now completed at this point since it's synchronous
promiseA = new Promise(function(resolve) {
var value = Date.now();
resolve(value);
console.log("this function has completed", value);
});
}
function drawPlayer() {
// this function is the main animation function and is called towards the end of function performAction so that the player gets nice, instant response to actions without waiting for server responses etc.
function animate() {
// this is the core animation function that performs the canvas API drawing for each frame of an animation
// if we have finished drawing all the animation frames, then we are OK to clear the timer
if (currentFrame == frames.length) {
clearInterval(timer);
// the drawPlayer function has now completed at this point
promiseB = new Promise(function(resolve) {
var value = Date.now();
resolve(value);
console.log("this function has completed", value);
});
}
}
// set up the locally scoped timer to run the animation function every frameDelay (about 20ms) for smooth animations
var timer = setInterval(function() {
animate();
}, frameDelay);
}
function textOverlay() {
// this function is a canvas drawing function that draws nice floaty text that fades out
// about a hundred lines of bog standard canvas api code here
// the actual, asynch drawing code. we delay the text overlay by about 500ms to better synchronise with animation actions first
setTimeout(function(){
// then we draw something and slowly reduce the opacity every frameDelay (about 20ms) until the text fades out
var interval = setInterval(function() {
// when our alpha is below zero, we know the text isn't on the screen anymore
if (alpha < 0) {
clearInterval(interval);
// the textOverlay function has now completed at this point
promiseC = new Promise(function(resolve) {
var value = Date.now();
resolve(value);
console.log("this function has completed", value);
});
}
}, frameDelay);
}, animationDelay);
}
function sendAction(data) {
// this function is called from performAction whenever an event needs to be sent to the server in a multiplayer game. bog standard stuff. nothing to see here, move along
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var data = JSON.parse(xhttp.responseText);
completeAction(data);
}
xhttp.open("GET", serverURL "?data=" data);
xhttp.send();
}
However this also doesn't work and produces similar results to #1 above.
I know I am missing something fundamental here in my first use of promises, but I am also sure based on reading all the MDN documentation (but perhaps not fully understanding it or misinterpreting it) that promises should be able to work for this use case.
What am I doing wrong?
CodePudding user response:
You're not using promises correctly. (That's understandable, they're confusing). Specifically, you're:
- creating empty Promises
- misusing
then()
.
Creating empty Promises
Currently, your promise is being created and resolved immediately.
When you create a promise, you pass it a function with a parameter (which is itself a function) named resolve
. The promise get completed when you call that resolve parameter. That Your asynchronous code needs to go inside this function, because you need to call resolve()
it only after your async code is done - or you can use a hack to get this function and call it elsewhere.
then()
When you call .then
, you're simply adding another function or promise that uses the return value of the previous promise in the chain, after that promise resolves. Since your promise has already resolved, the then()
executes and returns immediately, not doing you any good.
So how do you fix it?
Your code is a little difficult to stuff inside a promise, so you can use a little trick to resolve promises externally and combine it with async/await.
Let's look at implementing this for sendAction
:
// Change function to async; This means it returns a promise,
// and you can use async...await
async function sendAction(data) {
var resolver = {} // An object to smuggle resolve() out of scope
var done = new Promise(function(resolve) {
resolver.resolve = resolve // This is the function that resolves the promise
})
var xhttp = new XMLHttpRequest();
// note that our callback function is "async" now
xhttp.onreadystatechange = async function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var data = JSON.parse(xhttp.responseText);
await completeAction(data); // this will be async too
// Only now that all the asynchronous code is complete...
resolver.resolve() // ...do we resolve the promise
}
}
xhttp.open("GET", serverURL "?data=" data);
xhttp.send();
// The function will wait until the "done" promise is resolved
await done;
}
The async
and await
help write somewhat more readable and understandable code without having to muck about too much with promises, and and async functions return promises themselves.
Implemented for the rest of the code, using async/await:
async function performAction() {
// this is the function that is fired when the player presses a button to perform some action, for example "move 5 tiles"
// a few hundred lines of code to do stuff client-side like move validation etc.
var playerDrawn = drawPlayer(); // we now fire the client-side animation function so that players get instant feedback and don't need to wait for the server response in multi-player games
// if this is a multi-player online game, we now call a function to fetch data from the server, for example to check if this player is blocked from taking that move
if (gameType == "remoteHuman") {
await sendAction(data);
}
// otherwise, we don't need to contact the server if the player is playing a local AI game and can continue with the remaining actions
else {
await completeAction(data);
}
await playerDrawn
}
async function completeAction(data) {
// this function carries out the remaining tasks required on the client based on either the server response, or being called directly from performAction in local, single-player games
updateStats(); // update all the player's stats
await textOverlay(); // draw a nice, floaty text overlay that shows some numbers and fades out
}
function updateStats() {
// this function is maybe a hundred lines of standard, synchronous code that updates player statistics like health etc.
// we are at the bottom of the code, so the updateStats function has now completed at this point since it's synchronous
}
async function drawPlayer() {
// this function is the main animation function and is called towards the end of function performAction so that the player gets nice, instant response to actions without waiting for server responses etc.
var resolver = {}
var done = new Promise(function(resolve) {
resolver.resolve = resolve
})
function animate() {
// this is the core animation function that performs the canvas API drawing for each frame of an animation
// if we have finished drawing all the animation frames, then we are OK to clear the timer
if (currentFrame == frames.length) {
clearInterval(timer);
// the drawPlayer function has now completed at this point
resolver.resolve()
}
}
// set up the locally scoped timer to run the animation function every frameDelay (about 20ms) for smooth animations
var timer = setInterval(function () {
animate();
}, frameDelay);
await done;
}
async function textOverlay() {
// this function is a canvas drawing function that draws nice floaty text that fades out
// about a hundred lines of bog standard canvas api code here
var resolver = {}
var done = new Promise(function(resolve) {
resolver.resolve = resolve
})
// the actual, asynch drawing code. we delay the text overlay by about 500ms to better synchronise with animation actions first
setTimeout(function () {
// then we draw something and slowly reduce the opacity every frameDelay (about 20ms) until the text fades out
var interval = setInterval(function () {
// when our alpha is below zero, we know the text isn't on the screen anymore
if (alpha < 0) {
clearInterval(interval);
// the textOverlay function has now completed at this point
resolver.resolve()
}
}, frameDelay);
}, animationDelay);
await done;
}
async function sendAction(data) {
// this function is called from performAction whenever an event needs to be sent to the server in a multiplayer game. bog standard stuff. nothing to see here, move along
var resolver = {}
var done = new Promise(function(resolve) {
resolver.resolve = resolve
})
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = async function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var data = JSON.parse(xhttp.responseText);
await completeAction(data);
resolver.resolve()
}
}
xhttp.open("GET", serverURL "?data=" data);
xhttp.send();
await done;
}
Now that you've put all your logic inside performAction()
, you can use the promise it returns like so:
performAction().then(() => {
var value = Date.now();
console.log("all functions completed", value);
console.log("play can now be handed over to the other play");
nextPlayerTurn();
});
There's lots of optimizations you can make there to help make the code more elegant, but I tried to change it as little as possible and work with what you had.
The biggest suggestion I'd make is replace all of the XMLHttpRequest
stuff in sendAction()
with the Fetch API, which natively uses promises and is much more modern and easy to work with.
edit: Other suggested reading: