0

Is there any way to convert promise into string, or maybe is there another way how to handle this result. Im getting an error "You cannot use an argument of type "Promise " for a parameter of type "string"."

const pokemonImgs: string[] = [];

interface PokemonImg {
  img: string;
}

const getPokemonImg = async (id: number): Promise<PokemonImg> => {
    const pokemonUrl = await fetch(`https://pokeapi.co/api/v2/pokemon/${id}`);
    const pokemonImg = await pokemonUrl.json();
    return pokemonImg.sprites.back_shiny;
};

const getPokemons = async () => {
  try {
    for (let i: number = 1; i <= 20; i++) {
      pokemonImgs.push(getPokemonImg(i));
    }
  } catch (error) {
    console.error(error);
  }
};
  • 1
    Since `async` functions always return a `Promise` you need to await the return value like `await getPokemonImg(i)`; – Reyno Sep 28 '22 at 11:53

1 Answers1

0

Since the Promise is returned, you have to await to get the string.

const getPokemons = async () => {
  try {
    for (let i: number = 1; i <= 20; i++) {
      const image = await getPokemonImg(i);
      pokemonImgs.push(image);
    }
  } catch (error) {
    console.error(error);
  }
};
Shri Hari L
  • 4,551
  • 2
  • 6
  • 18
  • 1
    It's great to want to help! But this topic is **very well covered** by previous questions and their answers. Please don't post answers to obviously-duplicate questions. It clutters up the site, making good thorough answers harder to find, and can make it impossible for the OP to delete the question (if people start downvoting the question, for instance). – T.J. Crowder Sep 28 '22 at 11:56