J
J
jondoeonoe2018-07-03 16:39:02
JavaScript
jondoeonoe, 2018-07-03 16:39:02

How to do fetch correctly in my case (Promise pending)?

Good evening.
There is an array, using map I draw each element of the array.
There is a question on one moment connected with fetch. Here I am using the function
<img src={this.getPromoUrl(tweet.id, "image")} />

getPromoUrl = (id, param) => {
    const fetchData = this.getPromise(id, param);

    console.log(fetchData);

    return fetchData;
  };

  getPromise = async (id, param) => {
    let data;

    try {
      const response = await fetch(`https://someurl/api/v1/statuses/${id}/card?access_token=${process.env.REACT_APP_KEY}`);
      const json = await response.json();

      data = json[param];
    } catch (e) {
      console.log(e);
    }

    return data;
  };

But, as expected, I get Promise pending on return fetchData
// В консоле все ок, строка
    console.log(fetchData);

I have a question, how can I make it so that I adequately receive a string from fetchData, I just do not quite understand. Is it because getPromise is async? I just don't know how to be, I would be grateful for an example/solution in my case. It's been about an hour and a half killed on this ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-07-03
@jondoeonoe

getPromoUrl = async (id, param) => {
  const data = await this.getPromise(id, param);
  console.log(data);   
  this.setState({ data });
};

or:
getPromoUrl = (id, param) => {
  this.getPromise(id, param).then(data => {
    console.log(data);   
    this.setState({ data });
  });
};

Have a good look at the Promise API .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question