简体   繁体   English

Ajax 调用后如何同步更新值

[英]How to update value after Ajax call synchroniously

I'm fetching data from my node(express) backend server to react front end.我正在从我的节点(快速)后端服务器获取数据以对前端做出反应。 But when I try to access the array index values I get the output as undefined.但是当我尝试访问数组索引值时,我得到的输出是未定义的。 I sure am doing something wrong here.我肯定在这里做错了什么。 Appreciate if someone could help me.感谢有人可以帮助我。

Here's my server side code:这是我的服务器端代码:

const companyDetails = [];

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

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

Here's my client side code:这是我的客户端代码:

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

But when I console.log(arr);但是当我console.log(arr); it prints out the array.它打印出数组。 I just cant access each index value separately.我只是无法分别访问每个索引值。

当我没有指定索引时,这是推迟“arr”的输出

The problem here is that the axios call is an async call and the follow of your code is sync so when you execute this code javascript execute the sync code first then the async one so in this case the line of code onsole.log(arr[0]);这里的问题是axios调用是一个async调用,您的代码axiossync因此当您执行此代码时, javascript执行sync代码,然后执行async代码,因此在这种情况下,代码行onsole.log(arr[0]); is executed before the response comes from the server在响应来自服务器之前执行

Adding to below answer, fetchComNames is asynchronously updated the arr as you're using API call.添加到以下答案中, fetchComNames会在您使用 API 调用时异步更新arr You're accessing the data before it has been updated, that's why getting undefined .您在数据更新之前访问数据,这就是为什么要获取undefined

You can try this.你可以试试这个。

    
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()

API calls are asynchronous so you are accessing the array before it has its values in it. API 调用是异步的,因此您要在数组中包含其值之前访问该数组。 Try marking your enclosing function as async and awaiting the axios get so that the call is forced to synchronous.尝试将您的封闭函数标记为 async 并等待 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])
(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.
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM