Reputation:
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.
});
Upvotes: 1
Views: 1850
Reputation: 1092
Working off of @Yousaf 's post, using async/await
might make it easier to mentally visualize.
try {
const res = await fetch('/startGame', {
method: 'POST',
body: JSON.stringify({ username: username }),
headers: { 'Content-Type': 'application/json' },
});
await fetch('/lookingForAPlayer', {
method: 'POST',
body: JSON.stringify({}),
headers: { 'Content-Type': 'application/json' },
});
} catch (error) {
console.log(error);
}
Upvotes: 1
Reputation: 29344
You can use promise chaining along with fetch api
fetch('/startGame', {
method: 'POST',
body: JSON.stringify({username: username}),
headers: { 'Content-Type': 'application/json' }
})
.then(res => {
// do something with response
// make second request
return fetch('/lookingForAPlayer', {
method: 'POST',
body: JSON.stringify({}),
headers: { 'Content-Type': 'application/json' }
});
})
.then(res => { /* do something with response */ })
.catch(err => console.log(err));
Keep in mind that second POST
request will be sent only after first POST
request is successful and client has received the response from the server
Upvotes: 0