0

I'm testing a basic usage of async/await in Javascript and trying to reach a conclusion. So, based in this test I made, it is impossible to make the code completely stop and wait for the response ? If i want to make use o the data that come from json() I have to use only inside then() method ?

async function fetchData(str = ''){
    const response = await fetch(`https://rickandmortyapi.com/api/${str}`)
    const data = await response.json()

    console.log(data)
    
    return data
}

let res = null
fetchData('character').then(e => {
    console.log(e)
    res = e
})

console.log(`number of characters is ${res}`)

console output is:

index.js:16 -> number of characters is null
index.js:5  -> {info: {…}, results: Array(20)}
index.js:12 -> {info: {…}, results: Array(20)}

What would be a correct way to print the information using only async/await ?

  • `const res = await fetchData('qwerty');` – epascarello Mar 13 '23 at 13:43
  • TL;DR: no, it is not possible to return an asynchronous value (=which will be available *sometime later*) synchronously (=right now). – deceze Mar 13 '23 at 13:45
  • It is impossible (or highly inadvised) to "stop" javascript execution for any kind of wait. This is specifically why the `async` model exists, allowing you to write code that "looks" sychronous, but yields execution to other tasks while the wait is happening. – spender Mar 13 '23 at 13:46
  • @epascarello shows the "correct way to print the information using only async/await" in the first comment. – deceze Mar 13 '23 at 14:10
  • Define "make the code completely stop". If you mean "make it **look** like it stopped" you do it in `fetchData` when you `await fetch`. In your second snippet you **chose** to use `then` so the data is only available *(reliably)* inside the its handler. – Dave Newton Mar 13 '23 at 14:27

0 Answers0