soraraso42 / learning-journal

0 stars 0 forks source link

2024-04-13 async promise handling #32

Open soraraso42 opened 7 months ago

soraraso42 commented 7 months ago
const test = fetch("https://pokeapi.co/api/v2/berry/?/offset=20&limit=20")
test.then(test=>console.log(test.json()))
const test = fetch("https://pokeapi.co/api/v2/berry/?/offset=20&limit=20")
test.then(test=>test.json())

console.log(test)

the first version worked while the second did not reveals how asyn works. In the first ,the then() method is called on the returned promise, and the console.log() is called after the promise is returned and .json() finishes.

In the second, the console.log() on line3 is called right after line1 . In effect, on line2 then() waits for line1 to finish while console.log() does not wait. So when it "asks for" test variable, what is assigned to test at the time of line 3 call, that is, when the promise is still pending, is returned to the log() function.