Home > Net >  Problems trying to get and pass data from a promise [duplicate]
Problems trying to get and pass data from a promise [duplicate]

Time:09-21

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
});

CodePudding user response:

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.

  • Related