tarek hassan
tarek hassan

Reputation: 802

How to get node js to send axios request before executing the following code

I am making code to receive news from news API and send me daily emails with top headlines based on cron jobs.

I need to receive data first then map it into a variable, I added async await but for some reason it is not working.

If you run this code it will only print "Before summary" and that is it.

It won't get inside if condition however I made async await for that, so the server responses first and then goes on executing the code and have "news" to make summary.

const cron = require("node-cron");
const express = require("express");
const moment = require("moment")
const axios = require("axios")
app = express();
var news;
app.listen("3000")

//I removed my API key from the code and wrote 'MYAPIKEY'.
async function getNews(){
  let response = await axios.get('https://newsapi.org/v2/everything?q=bitcoin&from=2018-11-12&sortBy=publishedAt&apiKey=MYAPIKEY')
  .then( response =>
    news = response.data.articles
    )

}

getNews()
console.log('Before summary')
if (news) {
var summary = news.map( newsItem =>   newsItem.title )
console.log(summary)
}

Upvotes: 0

Views: 750

Answers (1)

Jitender
Jitender

Reputation: 7969

You don't need then if you are working with async

async function getNews() {
    try {
        let response = await axios.get('https://newsapi.org/v2/everything?q=bitcoin&from=2018-11-12&sortBy=publishedAt&apiKey=MYAPIKEY');
        var news = response.data.articles;
        if (news) {
            var summary = news.map(newsItem => newsItem.title) console.log(summary)
        }
    } catch (err) {
        console.error(error);

    }
}
getNews();

Upvotes: 1

Related Questions