`How to spell Promise correctly?
I
I
IvanIvanIvanIvanIvan2018-09-11 21:19:37
JavaScript
IvanIvanIvanIvanIvan, 2018-09-11 21:19:37

How to spell Promise correctly?

change has a function

export const getNews = async () => {
    let news;
    try {
      fetch(`https://newsapi.org/v2/top-headlines?country=us&apiKey='''''''''`)
        .then(res => res.json())
        .then(res => {
            news = res;
        })
    } catch(e){
      throw e;
    }
    return news;
};

It makes a request to the server and receives the news (I checked the output in the console)
How can I call this function correctly and get the news
getNews()
            .then(result => {
              console.log(result);
            })
            .catch(error => {
              console.log(error);
            });

My result outputs undefined

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stockholm Syndrome, 2018-09-11
@StockholmSyndrome

export const getNews = async () => {
  let news;
  try {
    news = await fetch(`https://newsapi.org/v2/top-headlines?country=us&apiKey='''''''''`).then(res => res.json());
  } catch(e){
    throw e;
  }
  return news;
};

V
Vladimir Proskurin, 2018-09-11
@Vlad_IT

You don't need to use try...catch, you use promises, and they have their own implementation of error handling.

export const getNews = async () => {
    return fetch(`https://newsapi.org/v2/top-headlines?country=us&apiKey='''''''''`)
        .then(res => res.json())
        .then(res => {
            return res;
        });
};

and then just use
getNews()
            .then(news => {
              console.log(news);
            })
            .catch(error => {
              console.log(error);
            });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question