return 来自箭头函数的变量 [JS]

return variables from arrow function [JS]

我有这个函数 getData,它将从 JSON 文件中读取 ID 列表。 ID 列表存储在 idsList 变量中,我需要在另一个函数中使用它。我如何 return 这个函数的值

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

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

您可以通过多种方式解决这个问题。例如:

// 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
}

// 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)  
    })  
}

你可以试试这个:

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

}