1

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()?

2
  • 2
    Possible duplicate of How do I return the response from an asynchronous call?
    – Adrian
    Commented Aug 29, 2018 at 12:18
  • The value returned from PHP is in the Promise, you can't 'unwrap' it. You'll have to use it only in async functions and await it or else do your work in a .then handler (don't forget you can attach them at any time). Commented Aug 29, 2018 at 12:20

2 Answers 2

1

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.

3
  • Okay, just so I get this right, if I do it the way you explained, does the codeexecution wait for the full execution of determineLoggedUser() just like it would if I used "await determineLoggedUser()"? Because if codeexecution doesn't wait, how can I be sure that "result" already contains the returned promise and is not "undefined" in a worst case scenario? Commented Aug 29, 2018 at 12:40
  • the code within the "then" section waits, yes. The whole point of "then" is to provide a way for code to always execute after the Promise is resolved (i.e. in this case, when the ajax request completed). If you're not clear on this, you should maybe study the Promise interface in more detail. So as long as the calls to your other, dependent functions are within that section, they will not be executed until it completes. Notice in the example above I moved your comment about "some other functions" inside there.
    – ADyson
    Commented Aug 29, 2018 at 12:56
  • BTW for clarity I just changed the code so that we don't have two variables both called "result". We now have "promise" and "response" which hopefully are more indicative of their actual purpose. When you referred to "result" potentially being undefined in your comment above, which one were you talking about? Neither of them would ever be undefined - the promise variable will always contain a promise object, whether it's resolved yet or not, and the response variable will always either be populated with data or be null, depending on what the server returns. It won't ever not be defined.
    – ADyson
    Commented Aug 29, 2018 at 12:58
0

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)

1
  • what's the purpose of returning the result of a console.log()? That doesn't make much sense. console.log isn't for returning values. And where are you returning it to, precisely? Also why two separate thens? Logging and returning a result could be done in one function. what is res.json() exactly? res will be undefined in your code.
    – ADyson
    Commented Aug 29, 2018 at 13:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.