Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async Function returns Promise pending

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)
like image 308
OpenSaned Avatar asked Jul 21 '26 10:07

OpenSaned


1 Answers

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:

  1. Your 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.
  2. await response.json needs to be await response.json().
  3. pokemonID should be passed as an argument, not just stuffed into a higher scoped variable.
  4. When calling 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);
});
like image 136
jfriend00 Avatar answered Jul 23 '26 00:07

jfriend00



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!