I am trying to do two post requests in JavaScript (client-side), but the second one seems to run before the first one is completed.
This is the code I have:
Client-side code:
$.post("/startGame", {username: username});
$.post("/lookingForAPlayer", {});
Server-side code:
var idPlayer;
app.post('/startGame', function(req, res) {
const idPlayerProm = new Promise((resolve, reject) => {
dbConnection.getIdPlayer(req.body.username).then(data => {
resolve(data)
});
});
Promise.all([idPlayerProm]).then(data => {
idPlayer = data[0];
console.log("idPlayer1: " + idPlayer) //Here idPlayer has a value
const gamePromise = new Promise((resolve, reject) => {
dbConnection.addGame(idPlayer).then(data => {
resolve(data);
});
});
Promise.all([gamePromise]).then(data => {
idGame = data[0];
});
})
});
app.post('/lookingForAPlayer', function(req, res) {
console.log("idPlayer2: " + idPlayer); //Here idPlayer is undefined
});
Result:
As you can see, it even prints idPlayer2
at first when should be printed after idPlayer1
.
I am guessing I need to do some sort of Promise
in the client side, but I am not sure how as I am new at doing them on the client-side.
Any help?
Update for @DanMossa (I cannot get the value I send from the server with his/her answer).
app.post('/startGame', function(req, res) {
dbConnection.getIdPlayer(req.body.username).then(data1 => {
dbConnection.addGame(data1).then(data2 => {
res.end(JSON.stringify([data1, data2]));
});
});
});
app.post('/lookingForAPlayer', function(req, res) {
//Here I will also res.end() as I do in /startGame.
});