Reputation: 802
I making API request to NewsAPI.org in node, If I simply use console log the response gets printed. Now I want it to return it in a var 'news' and it doesn't return it. Also I made the function return in 'updatedNews' still not working.
So the data is returned in console log but not saved in 'var'.
var news = 'news';
async function getNews() {
var responseNews = await axios
.get(
"https://newsapi.org/v2/top-headlines?country=us&apiKey=key"
)
.then( response => news = response.data.articles );
return responseNews;
}
var updatedNews = getNews()
console.log(news)
console.log(updatedNews)
Upvotes: 0
Views: 2267
Reputation: 183
var updatedNews = getNews()
Here your making async call and in the next line your expecting the result. But here async call is not being resolved yet. The way we can achieve this is updated below. here is the update code for same.
<!DOCTYPE html>
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
<body>
<script>
'use strict';
var news = ""
function f() {
return axios
.get(
"https://jsonplaceholder.typicode.com/todos/1"
)
.then(response => response.data.title);
}
f().then(news => console.log(news));
</script>
</body>
</html>
Upvotes: 1
Reputation: 4011
There are a bunch of issues with your code...
This should work:
const axios = require('axios');
async function getNews() {
const response = await axios.get(
'https://newsapi.org/v2/top-headlines?country=us&apiKey=key',
);
const news = response.data.articles;
console.log(news);
}
getNews();
Upvotes: 1