Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

194
Vistas
Axios function call won't return data

I'm sure this is an issue with my understanding/implementation. The issue is that I'm trying to return the ID of the created object into an array so that array can later be inserted into another object. Moving the .then() between the function, the call, nothing seems to work. Pushing to the array, assigning the value to the array via index doesn't seem to work. Any insights/guidance into what the root issue is and a path to resolve it is appreciated.

index.js

const contacts = document.getElementsByName('newContact');
const contactName = document.getElementsByName('contactName');
const contactTitle = document.getElementsByName('contactTitle');
const contactPhone = document.getElementsByName('contactPhone');
const contactEmail = document.getElementsByName('contactEmail');
let contactIDArray = new Array();
for (let i = 0; i < contacts.length; i++) {
  const name = contactName[i].value;
  const title = contactTitle[i].value;
  const phone = contactPhone[i].value;
  const email = contactEmail[i].value;
  var id;
  createContact(name, title, phone, email).then(function (res) {
    id = res.data.id;
    alert(res.data.id);
    return id;
  });
  alert(id);

contact.js

import axios from 'axios';

export const createContact = async (contactName, contactTitle, contactPhone, contactEmail) => {
  try {
    const res = await axios({
      method: 'POST',
      url: '/api/v1/contacts',
      data: {
        contactName,
        contactTitle,
        contactPhone,
        contactEmail,
      },
    });
    return res.data.id;
  } catch (err) {
    console.log(err);
  }
};
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

There are multiple problems I can see:

  1. As VLAZ states in the comment, you're trying to get the .data.id on a value that is already an id
  2. Creating a sequence of promises should be done using the tools provided by the Promise util (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all might be what you are looking for).

For instance I would go with something along those lines (not tested):

const contacts = document.getElementsByName('newContact');
const contactName = document.getElementsByName('contactName');
const contactTitle = document.getElementsByName('contactTitle');
const contactPhone = document.getElementsByName('contactPhone');
const contactEmail = document.getElementsByName('contactEmail');
let contactIDArray = new Array();

const requests = []

for (let i = 0; i < contacts.length; i++) {
  const name = contactName[i].value;
  const title = contactTitle[i].value;
  const phone = contactPhone[i].value;
  const email = contactEmail[i].value;
  var id;
  promise = createContact(name, title, phone, email).then(function (res) {
    const id = res.data.id;
    alert(res.data.id);
    return id;
  });
  requests.push(promise)
} 

Promise.all(requests).then(ids => {
    // This should contain the array of ids
    alert(ids)
})

Edit: Also, be careful about sharing result between synchronous and asynchronous calls, usually you would stay in the async world once you started your async tasks, as stated here: How to return data from promise

about 4 years ago · Juan Pablo Isaza Denunciar

0

I'm trying to return the ID of the created object into an array so that array can later be inserted into another object

Based on your request, I have a few things for you:

  1. Like jkoestinger's answer, do not use async/await or asynchronous functions (.then()) inside a loop unless you really need it.
  2. Do not return a property directly from the async call, you should return the whole object and get the ID. This is a good practice.

Please see the modified code below:

index.js

let contactPromises = [];

for (let i = 0; i < contacts.length; i++) {
  const name = contactName[i].value;
  const title = contactTitle[i].value;
  const phone = contactPhone[i].value;
  const email = contactEmail[i].value;
  
  contactPromises.push(createContact(name, title, phone, email));
}

let contacts = (contactPromises.length > 0) ? await Promise.all(contactPromises) : [];
let contactIds = contacts.map(contact => contact.id);
// use your contactIds here

axios

let res = await axios({
  method: 'POST',
  url: '/api/v1/contacts',
  data: {
    contactName,
    contactTitle,
    contactPhone,
    contactEmail,
  },
});

return res.data;   // <--- return res.data only, not the res.data.id
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda