0

i made a request to an api it returns an object it has property holding a string i stored the string in a variable named lyrics now if i console log the variable inside the async await function it gives the string but if i console.log the variable outside of async/ await it returns an empty string which is the value of the variable before i assigned the value of the property to it from the object

let lyrics='';
async function displayLyrics2(url){ 
const request = await fetch(url);
   const response= await request.json();
   console.log(response)
   lyrics+= response.result.lyrics;
   console.log(lyrics);
   }
displayLyrics2()
console.log(lyrics)
  • 1
    Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Liam Nov 11 '21 at 13:11
  • If you do `await displayLyrics2()` it will execute in the manner that your expecting – Liam Nov 11 '21 at 13:12
  • so is there a way to get the value outside my Async/await – BigDaddyTrump Nov 11 '21 at 13:56
  • 1
    Read the duplicate – Liam Nov 11 '21 at 13:57
  • i now understand the problem but i still don't know how to fix it in my code i mean where do i begin from u feel me? – BigDaddyTrump Nov 11 '21 at 15:06
  • I've already told you [one way](https://stackoverflow.com/questions/69928665/why-is-my-lyrics-variable-returning-an-empty-string-outside-async-await-functi?noredirect=1#comment123613502_69928665) of "fixing it" – Liam Nov 11 '21 at 15:15
  • they only thing in my head right now in how to fix it so to put an my async/await function inside of another sycnhronous function and execute it – BigDaddyTrump Nov 11 '21 at 15:25
  • Ok, there is no way to return the value, so forget about that. The function does not execute in the order your expecting (full-stop). If you simply want to log the value and the parent function is not async then just use a `then`: `displayLyrics2().then(t => {console.log(t); });` – Liam Nov 11 '21 at 15:27
  • well i dont want to log the value i need to use the value and display in another page but there is no way of getting the value outside of async/await :( – BigDaddyTrump Nov 11 '21 at 15:33

0 Answers0