【问题标题】:How to update value after Ajax call synchroniouslyAjax调用同步后如何更新值
【发布时间】:2021-03-03 08:56:13
【问题描述】:

我正在从我的 node(express) 后端服务器获取数据以响应前端。但是当我尝试访问数组索引值时,我得到的输出是未定义的。我肯定在这里做错了什么。感谢有人可以帮助我。

这是我的服务器端代码:

const companyDetails = [];

companies.forEach((company) => {
    companyDetails.push(company);  
});

app.get("/api/companies", (req, res) => {
    res.json(companyDetails)
});

这是我的客户端代码:

let arr = [];

    function fetchComNames() {
        axios.get('/api/companies').then(res => {
          for(let i=0; i<=4; i++) {
              arr.push(res.data[i].name)
          }
        })
    }

    fetchComNames();

    console.log(arr[0]);   //undefined

但是当我console.log(arr); 时,它会打印出数组。我只是不能单独访问每个索引值。

【问题讨论】:

    标签: javascript node.js arrays reactjs express


    【解决方案1】:
    (async () => {
        const arr = [];
    
        // Marking this function as async function so that 
        // we can use await to wait until result returning 
        // before further executing code below
        async function fetchComNames() {
            // I don't have access to you API
            // I resolve data after 1 second to simulate Ajax call here
            return new Promise(function(resolve, reject) {
                setTimeout(function() {
                    resolve({
                        data: [{
                            name: "1"
                        }, {
                            name: "2"
                        }, {
                            name: "3"
                        }, {
                            name: "4"
                        }]
                    });
                }, 1000);
            }).then(res => {
                return res.data.map(each => each.name)
            });
        }
    
        // You are calling Ajax call via Axios, which is a Promise. 
        // It is executed asyncrhoniously. 
        // If you need to use result from this call, 
        // you need to wait until result returning from async call. 
        // You can achieve it with await.
        
        // Update existing array
        arr.push(...(await fetchComNames()));
    
        // After await, arr should contain result you expected.
        console.log(arr[0]);
    
        // There reason why your version is not working 
        // is because you are accessing the first cell of arr 
        // wihich is still empty as the Axios is still running 
        // and you are not waiting until it returns result.
    })();
    

    【讨论】:

    • 非常感谢您的解释。但是我需要从这个函数中访问这个数组的值。我似乎无法在此功能之外做到这一点。有什么办法可以做到吗?
    • 请给我更多代码。如果您只需要将更多项目添加到现有数组中,这不是问题,我将更新我的代码
    • 这解决了我的问题,非常感谢,你帮了很多忙!
    【解决方案2】:

    添加到下面的答案中,fetchComNames 在您使用 API 调用时异步更新为 arr。您在数据更新之前访问数据,这就是为什么要获得undefined

    你可以试试这个。

        
    const fetchComNames = async () => {
        try {
          const response = await axios.get('/api/companies')
          const array = response.data.map(c => c.name)
          OR
          const array = []
          for (let i = 0; i<= 4; i++) {
            array.push(response.data[i].name)
          }
          console.log(array[0])
        } catch(err) {
          console.error(err)
        }
    }
    
    fetchComNames()
    

    【讨论】:

      【解决方案3】:

      API 调用是异步的,因此您在数组中包含值之前访问该数组。尝试将您的封闭函数标记为异步并等待 axios get 以便强制调用同步。

      let arr = [];
      
          async function fetchComNames() {
            const fetched = await axios.get('/api/companies');
                for(let i=0; i<=4; i++) {
                    arr.push(fetched.data[i].name)
                }
              
          }
      
          fetchComNames();
      
          console.log(arr[0])
      

      【讨论】:

      • 不过,这将提供undefined
      【解决方案4】:

      这里的问题是axios 调用是async 调用,而您的代码后面是sync,所以当您执行此代码javascript 时先执行sync 代码,然后再执行async在这种情况下,代码行是onsole.log(arr[0]); 在响应来自服务器之前执行

      【讨论】:

        猜你喜欢
        • 2016-04-20
        • 2012-01-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-30
        相关资源
        最近更新 更多