0

I'm making a promise chained fetch call to an API and using it to get the desired data from it. I can't figure out how to save the resulting array which I am logging to the console and then export it to use it another javaScript file.

fetch('http://api.waqi.info/feed/delhi/?token=66cc9b64ec97aff8a78266ca41b082edf3e9a65a')
  .then(res => res.json())
  .then(response_body => Object.values(response_body.data.iaqi).map(({v}) => v))
  .then(console.log)
  • You need to export an `async` function wrapping this call, not the array. Then call (`await`) the function from the other module. –  May 02 '20 at 11:24
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) –  May 02 '20 at 11:25
  • @ChrisG so you mean to wrap this fetch call in something like const getData = async function(){.......} , then export it from this file using module.exports . Importing it in the other file and using it like const data = await module_name.getData() ? – Sarthak Kundra May 02 '20 at 11:32
  • Yes, exactly like that –  May 03 '20 at 09:26

1 Answers1

1

You can just export your fetch call in a function and return your Promise.
Here is a minimal example:

// == api.js ==
export const getData = () => {
  return fetch('http://api.waqi.info/feed/delhi/?token=66cc9b64ec97aff8a78266ca41b082edf3e9a65a')
    .then(res => res.json())
    .then(response_body => Object.values(response_body.data.iaqi).map(({v}) => v))
    .then(console.log)
}



// == otherfile.js ==
import { getData } from './api.js'

const myFunction = () => {
  getData().then(res => {
    // do your stuff
  })
}

// Async/await style
const myFunction = async () => {
  const res = await getData()
}
Simon Bruneaud
  • 2,263
  • 2
  • 12
  • 24