#How to wait inside then

11 messages · Page 1 of 1 (latest)

dim spear
#

How do you call a function from within fetch.then after the data is fetched? I've also tried just returning the data, but that also fires before the data comes back.

Below, the console.log(data) line waits for the data, but getElements is called immediately, resulting in a console.log of "undefined yo".

        fetch('https://opentdb.com/api.php?amount=5&category=9&difficulty=easy&type=multiple')
            .then(res => res.json())
            .then(data => {
                console.log(data)
                getElements(data)
            })
            .catch(error => { console.log(error); })
    }

    function getElements(something) {
        console.log(something, "yo")
}

  getQuestions()```
coarse cliff
#

just give it a try,

.then (data => {
console.log(data)
Return data
})
.then(data => getElements(data))

🤔

coarse cliff
#

but that doesn't make sense as .then will resolve and give the data to do something...

I think u have something not going as thinking
Maybe once check like this..

fetch(url).then((response) => console.log(response.status))

lofty forge
#

Uh... are you sure? When I run your original code @dim spear I get:

{response...} 'yo'

So it appears to be working just fine...

dim spear
dim spear
coarse cliff
#

Um...3 times? function console and function?

bleak imp
#

The original code fragment that's posted above also works perfectly fine for me.

lofty forge
brittle oak
#

I think @lofty forge is right. Because, if the console.log works with the correct data, it means the data is ready at that point, so also your function should work accordingly

bleak imp
#

The posted code snippet essentially implements the asynchronous callback pattern -- except the callback is a global function, not one passed as a parameter.