【问题标题】:return variables from arrow function [JS] [duplicate]从箭头函数返回变量[JS] [重复]
【发布时间】:2022-01-03 12:28:47
【问题描述】:

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

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

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

【问题讨论】:

标签: javascript function return arrow-functions


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    你可以试试这个:

    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
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-04
      • 1970-01-01
      • 1970-01-01
      • 2021-04-03
      • 2017-06-25
      • 2019-11-25
      • 1970-01-01
      相关资源
      最近更新 更多