I don't understand why i get Promise { <pending> } since i used async/await
this is my code
const fetch = require("node-fetch")
function getRandomPokemon() {
var pokemonID = Math.floor(Math.random() * 851);
console.log("The Pokemon Id is " + pokemonID);
return pokemonID
}
async function getJSON() {
let response = await fetch('https://pokeapi.co/api/v2/pokemon/'+ pokemonID);
var json = await response.json
}
var pokemonID = getRandomPokemon()
var json = getJSON()
console.log(json)
All async functions return a promise - always. Using await inside an async function suspends the execution of that function until the promise you are awaiting resolves or rejects, but an async function is not blocking to the outside world. An await does not suspend execution of the whole js interpreter.
At the point of the first await in the async function your function returns a promise back to the caller and the caller continues to execute. That promise is then resolved or rejects when the function eventually completes its work sometime in the future.
I don't understand why i get Promise { } since i used async/await
Because all async functions return a promise.
There are numerous issues in your code:
getJSON() function has no return value. That means that the promise it returns resolves to undefined so there's not way to communicate back its value.await response.json needs to be await response.json().pokemonID should be passed as an argument, not just stuffed into a higher scoped variable.getJSON(), you have to use .then() or await on it to get the resolved value from the returned promise.You may also notice that your getJSON() function has no return value. That means that the promise it returns also resolves to undefined. And, await response.json needs to be await response.json().
Your code needs to be more like this:
async function getJSON(id) {
const response = await fetch('https://pokeapi.co/api/v2/pokemon/'+ id);
const json = await response.json();
return json;
}
const pokemonID = getRandomPokemon();
getJSON(pokemonID).then(data => {
console.log(data);
}).catch(err => {
console.log(err);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With