-1

I decided to create a special service aka ES6 class with needed functions to get data from API and then in index.js I could create an instance of the class and work with it. Unfortunately, when I try it, it always returns

Promise {<pending>}

and I don't really know what to do.

nytService.js:

export default class NYTService {
    urlBase = "https://api.nytimes.com/svc/topstories/v2/";
    category = "world";
    apikey = *my api key* ;

    async getNews(category = this.category) {
        let url = `${this.urlBase}${category}.json?api-key=${this.apikey}`;

        let res = await fetch(url)
        let data = await res.json();
        
        return data;
    }
}

index.js:

import NYTService from "../services/nytService.js";

let nytService = new NYTService();

async function getNewsFinally() {
    let res = await nytService.getNews();

    return res;
}

console.log(getNewsFinally());

I did tried different things with the getNewsFinally function, did various .then chains, nothing helped

Andriy
  • 25
  • 3
  • 2
    Your getNews method doesn't return anything... (or rather, as an async function, it returns a promise of nothing). – jonrsharpe May 22 '22 at 14:27
  • 1
    i'm confused. I've used this pattern before and it works....why would it not work if OP is doing `let data = await res.json()` – chovy May 22 '22 at 14:33
  • 4
    @Andriy: since getNewsFinally is an async function, it will return a promise. Thus, `console.log(getNewsFinally());` logs a promise. If you want to interact with the value inside the promise, then put your code in an async function and await that promise. `async function someFunction() { console.log(await getNewsFinally()); }` – Nicholas Tower May 22 '22 at 14:35
  • @chovy — The code in the question has been edited since jonrsharpe's comment. – Quentin May 22 '22 at 14:35

1 Answers1

-2

See if this tells you why:

    async getNews(category = this.category) {
        let url = `${this.urlBase}${category}.json?api-key=${this.apikey}`;

        try {
           let res = await fetch(url)
      
           if (!res.ok) {
               return res.statusText;
           }
           
           return await res.json();
        } catch(err)  {
           console.error(err);
           throw new Error(err);
        }
      }
chovy
  • 72,281
  • 52
  • 227
  • 295
  • That might explain why `fetch` is throwing an error … if `fetch` was throwing an error, but there's no sign that it is. The question is asking why `getNews` is returning `Promise {}` – Quentin May 22 '22 at 14:37
  • 1
    getNews is marked as async which means it'll return a Promise no matter what, so you need to "unpack" that promise, ex console.log(await getNewsFinally()) or equivalent getNewsFinally().then(res => console.log(res)) – Victor May 22 '22 at 14:52