Reputation: 179
I have the following JScode
function DetermineLoggedUser(){
return $.post('determineLoggedUser.php',{
}).then((result) => {
loggedUser = result;
})
The php looks like this:
<?php
session_start()
if(ISSET($_SESSION["loggedUser"])) {
echo $_SESSION["loggedUser"];
}else{
echo "'userNotLogged'";
}
?>
Now, I want DetermineLoggedUser()
to return the value of loggedUser
after it has been set by $.post AJAX call.
At the same time, I want the function calling DetermineLoggedUser()
to wait, using async/await.
So it would look kinda like this:
async function callingSeveralFunctions(){
//some functions
var result = await determineLoggedUser();
//some other functions which need to wait for determineLoggedUser()
}
function DetermineLoggedUser(){
return $.post('determineLoggedUser.php',{
}).then((result) => {
loggedUser = result;
})
callingSeveralFunctions();
So, since I need to return the promise created by the AJAX call in order to make "await" work, I wonder how I can at the same time return the value set to loggedUser
inside determineLoggedUser()
?
Upvotes: 1
Views: 73
Reputation: 61983
You've got the first bit right - you're correct in returning the Promise from your DetermineLoggedUser()
function. The calling code can then attach a .then()
to that Promise object (as opposed to attaching it within the DetermineLoggedUser function, which isn't so useful) in which you can retrieve the value, and then execute whatever other functions you need which depend on it.
function callingSeveralFunctions(){
//some functions
var promise = determineLoggedUser();
promise.then((response) => {
loggedUser = response;
//some other functions which need to wait for determineLoggedUser() - calls to these need to go inside the callback, here
});
}
function DetermineLoggedUser(){
return $.post('determineLoggedUser.php',{});
}
callingSeveralFunctions();
You can't escape the fact that it's asynchronous, but you can work with it better.
Upvotes: 1
Reputation: 2187
Each promise, need to return something, in your case, then you call you file determineLoggedUser.php
he go directly into your then
function, expected that you return nothing.
Try something like that :
const ajax = $.post('determineLoggedUser.php',{
}).then(result => {
return res.json(); // In case of backend return json...
}).then(data => {
return console.log(data);
});
console.log(ajax)
Upvotes: 0