-1

i have a function , i need to delay its return until a value is set (by calling another function call_api basically i need to wait for second function result to be able to return the first function result )

here is what ti got

 function getList(s, p)
{

  var output = false  ;
  call_api(s , p , function(result){
    console.log(result);
    output =  result;
  })

  while (output == false )
  {
    1 ;
  }
  return output ;

}

but it wont work while somehow is messing thing up is there a way to solve this ?

ps : i know about promise / async function but i cant use them (its a test i ant use them in the test )

hretic
  • 999
  • 9
  • 36
  • 78
  • 1
    It's impossible to do this without Promises. I'm not sure why you're restricted from using those but you should probably tackle that. – VLAZ Mar 17 '20 at 13:01
  • @VLAZ im trying to solve this problem https://stackoverflow.com/q/60722260/5796284 – hretic Mar 17 '20 at 13:03
  • You have to use Promise or you can wait for some random time(but it will not guarantee results). – Prabhjot Singh Kainth Mar 17 '20 at 13:04
  • Well, it's still not possible. Nothing changed over the last 45 minutes to make async code convertible to sync. – VLAZ Mar 17 '20 at 13:04
  • 1
    @PrabhjotSinghKainth waiting will not help - if want to return from a function synchronously, you have to block the thread, which means that you aren't able to process the response for the async request. – VLAZ Mar 17 '20 at 13:05
  • 1
    You can't do this while since you will crash your browser. – Elias Soares Mar 17 '20 at 13:09

1 Answers1

0

You could do it using Promises, using a callback, or by checking the value every interval, using setTimeout. You can't do otherwise by definition of the Javascript language.

Using promises:

async function getList(s, p) {
  return await new Promise(resolve => call_api(s, p, result => resolve(result)));
}

Using callback:

var output = false;
call_api(s, p, result => {
  output = result;
  callback();
});

function callback() {
  // rest of code
}

Using setTimeout:

 var output = false;
 call_api(s, p, result => output = result);
 checkOutput();

 function checkOutput() {
   if (output === false) {
     setTimeout(checkOutput, 100);
   } else {
     // rest of code
   }
 }
ariel
  • 15,620
  • 12
  • 61
  • 73