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

163
Vistas
Problems trying to get and pass data from a promise

I am doing a job with a colleague, in which he chooses ajax to make requests to a web service, and I use fetch to make a request to an external api, I am running into a problem and it is that at the time of obtaining the data From the api through fetch it brings me the data after a certain time, but when I pass that data through ajax it sends the empty variable, which is logical because the fetch response takes a while to fill my variable, like this that what I try is to put a setTimeout in the ajax to wait a while and that it executes after my fetch request fills the data, but this does not work and does not perform any process:
This is my JavaScript:

$("body").on('click', '#MainContent_lnk_actualizar_foto', e => {
    e.preventDefault();
    let Archivo = $('#MainContent_file_foto')[0].files[0];
    let ubicacion = '';
    let params = new URLSearchParams(location.search);
    let Id_Usuario = params.get('Id_Usuario');
    const datos = new FormData();
    datos.append('imagen', Archivo);
    datos.append('ubicacion', 'perfil');
    fetch(`http://192.168.0.37:52456/api/Archivos/`, {
        method: 'POST',
        body: datos
    }).then(res => res.json())
        .catch(error => console.error('Error:', error))
        .then(response => {
            ubicacion = response.lugar
        })
        
    setTimeout(() => {
        $.ajax({
            type: 'POST',
            url: 'WebService_V_Perfil.asmx/SubirArchivos',
            data: '{"Archivo": "' + ubicacion + '","Id_Usuario": "' + Id_Usuario + '"}',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: result => {
                console.log(result);
                console.log(ubicacion);
            }
        })
    }, 3000
});
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Besides the syntax errors in your code, the only way you can use the values that return from the fetch call is by putting the code that process those results in a then block but leave the catch block to the end. Otherwise, in this case your code will not run as expected as the second then() block is expecting something that the previous catch() doesn't return.

fetch(`http://192.168.0.37:52456/api/Archivos/`, {
  method: 'POST',
  body: datos
})
.then(res => res.json())
.then(response => {
  const ubicacion = response.lugar;
  $.ajax({
    type: 'POST',
    url: 'WebService_V_Perfil.asmx/SubirArchivos',
    data: '{"Archivo": "' + ubicacion + '","Id_Usuario": "' + Id_Usuario + '"}',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: result => {
      console.log(result);
      console.log(ubicacion);
    }
  })
})
.catch(error => console.error('Error:', error))

Also, I don't think you need to use ajax to do what the same task as fetch does.

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