managing commitments in TypeScript

Is there a way to convert a promise into a string, or is there another method for handling this result? I am encountering an error stating "You cannot use an argument of type 'Promise' for a parameter of type 'string'."

const pokemonImages: string[] = [];

interface PokemonImage {
  img: string;
}

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

const getMorePokemons = async () => {
  try {
    for (let i: number = 1; i <= 20; i++) {
      pokemonImages.push(getPokemonImage(i));
    }
  } catch (error) {
    console.error(error);
  }
};

Answer №1

When you receive the Promise, remember to use await in order to access the string.

const fetchAllPokemonImages = async () => {
  try {
    for (let index: number = 1; index <= 20; index++) {
      const pokemonImage = await getImageForPokemon(index);
      allPokemonImages.push(pokemonImage);
    }
  } catch (error) {
    console.error(error);
  }
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What causes the sudden change in value of this array?

I can't seem to figure out what's going on with this question. It might be something silly, but I haven't been able to find any clues. Here is the array in question: const superVillains = [ { value: '1', label: 'Thanos&apo ...

Updating a particular element within nested arrays: best practices

I have developed a data table containing student records using material UI. Each row represents a different student array with a fee verification button. My goal is to change the fee status when the button is clicked for a specific student, but currently t ...

Scrolling text box utilizing Jquery

Currently, I am utilizing a scrolling box that functions well * view here * under normal circumstances. However, when there is an extensive amount of content below it, such as: <article class="content"> ...

Click on the sort icon in React JS to change its state

I need to update the sort icon in my table header when a user sorts a column. Here is the current implementation of my sorting function: var headerColumns = []; var IconType = 'triangle'; var IconSort = 'top'; var onToggleO ...

The content of InnerHtml does not appear on the screen

I am currently building a web project using HTML and Bootstrap, however, I am facing an issue where my content is not showing up in the browser. Below is the code snippet that I am working with: let str = "" for (let item of r.articles) { s ...

When using Protractor with Typescript, you may encounter the error message "Failed: Cannot read property 'sendKeys' of undefined"

Having trouble creating Protractor JS spec files using TypeScript? Running into an error with the converted spec files? Error Message: Failed - calculator_1.calculator.prototype.getResult is not a function Check out the TypeScript files below: calculato ...

Hinting the type for the puppeteer page

I am trying to type hint a page variable as a function parameter, but I encountered a compilation error. sync function than_func(page:Page) ^ SyntaxError: Unexpected token: ...

The variable "theme" is referenced prior to being initialized

https://i.stack.imgur.com/QL0pa.png One of the variables in my code, theme, is set to be assigned a value from a for loop: let theme: Theme for (const themeObj of themeList) { const [muiThemeName, muiTheme] = Object.entries(themeObj)[0]!; if (muiThem ...

Updating Angular 9 values using a fixed object

I am dealing with a patch value here where I simply pass an object to it. this.formPesquisar.controls['daniloTeste'].patchValue(this.dadosVisualizar.daniloTeste); However, I would like to pass a static object instead, something like: this.formPe ...

Placing a div over a JavaScript element

Is it feasible to overlay a div(1) with a background image on top of another div(2) that contains JavaScript (like Google maps API v3)? I have experimented with z-index without success, and I am unable to utilize absolute positioning because I depend on t ...

React Type Mutation response feedback is a valuable tool for receiving input

I am facing an issue with passing the mutation success response in my code. I have a file named change-email.tsx which calls a component file updateEmail.tsx containing a mutation function. The submit function is working fine, but I cannot figure out how t ...

Restricting the Vue for-loop results to display only the current item in use

Currently, I am utilizing a for-loop to retrieve all of my posts, followed by employing a partial to obtain a list of all the usersThatUpvoted on that post. <div v-for="p in posts" style="padding: 16px"> <div> &l ...

Struggling with integrating jQuery append into Backbone.js

Having trouble using jQuery.append() and backbonejs. Currently, when attempting to append, nothing happens (except the jQuery object is returned in the immediate window) and the count remains at 0. Manually adding the element has not been successful. I als ...

Preloading images before loading a div using JavaScript

Can you walk me through implementing object first and then mergeObject in JavaScript? I have an interesting scenario where I need to display the original list followed by a merged list after a short delay. How can I achieve this using JavaScript? Specific ...

Every time I attempt to reuse my components, they keep piling up on top of each other

I'm facing an issue where I need to reuse components I've created multiple times while rendering dynamic content. However, when I attempt to render them, they end up stacking on top of each other in the same position. Each time I render ...

How can I convert a string number with leading zeros into a string in a node.js environment?

When rendering a page, I pass the id as a string (e.g. 001, 002) but at the client side, I receive it as a number (e.g. 1, 2). res.render('leafletDemo',{id:userID,latitude:latitude,longitude:longitude}); Is there a way to keep the id as a str ...

What is the process for configuring my form to automatically send to my email upon clicking the send button?

I found this code snippet on a website and I'm trying to figure out how to make the 'Send!' button redirect users to my email address with their message, name, and email included. Can anyone help me solve this issue? I attempted to add my e ...

Guide to sending back an Observable within Angular 4

Inside my authProvider provider class, I have the following method: retrieveUser() { return this.afAuth.authState.subscribe(user => { return user; }); } I am looking to subscribe to this method in a different class. Here is an example ...

Ensure that the number is valid using Express Validator in Node.js

One thing that I've noticed when using express validator is the difference between these two code snippets: check('isActive', 'isActive should be either 0 or 1').optional({ checkFalsy : false, nullable : false }).isInt().isIn([0, 1 ...

Show only a cropped section of a resized image within a div

I have a script that calculates the best region of an image to display within a specific div size. This calculation is done in PHP and generates a JSON output like this: {"scale":1.34,"x1":502,"x2":822,"y1":178,"y2":578} The image in question has dimensi ...