Use async function successfully when create new object automatically [duplicate]

  ecmascript-6, es6-class, javascript, node.js

I want to run the code below successfully.

import newsapi from "newsapi";

const NewsAPI = new newsapi('***************************');

class newsApiHeadlines {

    constructor () {
        this.init();
    }

    async init () {
        this.newsApiRes = await NewsAPI.v2.topHeadlines({
            country: 'us',
        });
    }

    getTopHeadlineTitle () {
        return this.newsApiRes.articles[0].title;
    }

}

let objNewsApi = new newsApiHeadlines();
console.log(`Title:n${objNewsApi.getTopHeadlineTitle()}`);

Of course, the code resulted in TypeError: Cannot read property 'articles' of undefined.

I know that inserting await objNewsApi.init(); into between let objNewsApi = new newsApiHeadlines(); and console.log(`Title:n${objNewsApi.getTopHeadlineTitle()}`); works.

However I want to run the code above successfully without using await objNewsApi.init(); outside class definition with only let objNewsApi = new newsApiHeadlines(); and console.log(`Title:n${objNewsApi.getTopHeadlineTitle()}`);.

How can I make the constructor() and/or init() of the newsApiHeadlines class definition?
Is there any way to do this?

Source: Ask Javascript Questions

LEAVE A COMMENT