简体   繁体   中英

How can I return the result from this AJAX call?

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

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM