0

I have this function getData which will read in a list of IDs from a JSON file. the list of IDs is stored to the idsList variable which i need to use inside another function. How do i return the value from this function

function getData(){
    fetch("JSONitemIDsList.json")
    .then(response => response.json())
    .then(data => {
        let idsList = data.ids 
        //return idsList      
    })  
}

function myFunc(idsList) {
     //do something with idsList
}
logan9997
  • 73
  • 1
  • 5
  • 4
    Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Sven Eberth Jan 03 '22 at 12:29
  • you can use async-await – ParthPatel Jan 03 '22 at 12:31
  • what if you call `myFunc` in the success `then` call? ```.then(data => { let idList = data.ids; myFunc(idList); })``` – ElTi-42 Jan 03 '22 at 12:43

2 Answers2

2

You can approach this in many ways. For example:

// with async / await
async function getData() {
    try {
        const rawData = await fetch("JSONitemIDsList.json")
        const data = await rawData.json()
        return data
    } catch (err) {
        // handle error here
        console.log(err)
    }
}

async function myFunc() {
    const idsList = await getData()
     //do something with idsList
}

or

// define first
function myFunc(idsList) {
     //do something with idsList
}

function getData(){
    fetch("JSONitemIDsList.json")
    .then(response => response.json())
    .then(data => {
        // function call
        myFunc(data.ids)  
    })  
}
ABDULLOKH MUKHAMMADJONOV
  • 4,249
  • 3
  • 22
  • 40
0

You can try this:

const reqResponse = fetch("JSONitemIDsList.json")
    .then(response => response.json())  
    // I am not sure, if your data is already in the format that you need, otherwise, you can run one more .then() to format it

}

const getIdList= async () => {
const idList = await reqResponse;
console.log(idList)
// use idList to access the information you need

}
Deniz Karadağ
  • 751
  • 3
  • 8