0

I'm trying to create on a function that makes an axios request to a certain API and returns the data it gets back. I understand it has to be asynchronous, and I'm trying to build the function like that in NodeJS, but it keeps giving me a "promise pending" and doesn't return the data. It will do a console log, but I need to get the data returned whenever I call this function. The code I'm working with:

import axios from 'axios';

export default function simple() {
    const url = 'https://api.somerandomfakeurl.com/'

    return getData(url)
}

async function getData(url){
    const data = await axios(url).then(response => { return response })

    return data
}

So when I call on the simple() function, I want to get the response data. Anyone knows what I'm doing wrong? Thanks!

Andy
  • 1
  • Yes, `getData` returns a promise, and so will therefore `simple`. No way around that. – deceze Oct 12 '20 at 14:09
  • @Andy Welcome but you misunderstand async await. An async function always return a promise. You would need to handle that or make your other function Async, but that then means that function is returning a promise. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise. – JGleason Oct 12 '20 at 14:10
  • `const myData = await simple()` or `simple().then(myData => ...)` – Reyno Oct 12 '20 at 14:11
  • You nee do make simple an `async` function: `export default async function simple() {` and then `await` the `getData()` function call: `return await getData(url)` – a1300 Oct 12 '20 at 14:12
  • FYI: `response => { return response }` can just be `response => response.data`. – Reyno Oct 12 '20 at 14:13
  • @a1300 That still means `simple` returns a promise, because *it* is `async`… – deceze Oct 12 '20 at 14:13
  • @deceze yes, `async` all the way :) Would you return `getData(url)` without `await`? It is a taste issue isn't it? – a1300 Oct 12 '20 at 14:17
  • @a1300 No big difference either way. – deceze Oct 12 '20 at 14:18

0 Answers0