0

I'm having problem with async function, in this senario, i want to return true outside async function after it run successful, but i still stuck, here is example of that


const returnSomethingIfHaveData = () => {
  const someAsyncFunc = async () => {
    try {
      const data = await fetch('https://dummyjson.com/products/1').then(()=>true)
      return data
    } catch (e) {
      console.log(e);
    } 
  };
  if(someAsyncFunc().then(data=>data)===true) return true
  else if(someAsyncFunc().then(data=>data)===false) return false
  
  
};
console.log(returnSomethingIfHaveData()) // ==> always return nothing

Why it always false, and how to make it right? I mean it return true after it finish or i mean how to make it wait until api call done, mean how to make it return true always?

CODEforDREAM
  • 863
  • 1
  • 8
  • 24
  • "*how to make it wait until api call done*" - this is impossible. Best you can do is return a promise, and have the caller wait for it: `console.log(await someAsyncFunc())` or `someAsyncFunc().then(console.log)` – Bergi Jan 11 '23 at 10:34
  • Hi @Bergi, but we can't not return value of `someAsyncFunction` ? Can we use that to be a return value of `returnSomethingIfIHave`? – CODEforDREAM Jan 11 '23 at 10:50
  • The return value of `someAsyncFunction` is a promise. You can return that promise, you cannot immediately return the value that the promise will fulfill with later. – Bergi Jan 11 '23 at 12:03

0 Answers0