简体   繁体   中英

Issue looping through an object and adding to another

So I am trying to get some data from an API do some translation on it and return the values. This is pulling data from hubspot's hubdb API but when the data returns you do not get the field names back so I need to run it through a function to get the field names. I was able to successfully do this on a single row using the following.

return axios.get('urltoapi').then((res) => {
 const row = res.data;
 return convertHubdbKeyValues(table_name, row.values).then((details) => {
  return {
   details,
  };
 });
});

I have then tried to loop through a number of rows to build an array of data but all I get back is an empty array, I'm sure I'm doing something very basic wrong here

return axios
 .get(getRowByQueryUrl(table_details.table_id, query))
 .then((res) => {
  var bookings = [];
  this.data = res.data;
  this.data.objects.forEach((item) => {
   return convertHubdbKeyValues(table_name, item.values).then(
    (updatedValues) => {
     bookings.push(updatedValues);
    }
   );
  });
  return bookings;
 });

In your current implementation, the bookings array is returned before the asynchronous calls inside the forEach are complete. One way to get around this is to use Promise.all :

return axios
 .get(getRowByQueryUrl(table_details.table_id, query))
 .then((res) => {
  const promises = res.data.objects.map(item => convertHubdbKeyValues(table_name, item.values))
  return Promise.all(promises)
 });

The top-level function will return a promise that resolves to an array of updatedValues , as you call them above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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