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

100
Vistas
How do I wait on a function to return to a global variable before continuing the script?

This is my function and I am wondering how I would go about waiting on the global variable so I could then use the list in another function. I know this isn't the best practice in javascript but not understanding how I would wait on it is bothering me

function load_csv_async(){
    return new Promise((resolve,reject) => {
        const fileInput = document.querySelector('input');
        fileInput.addEventListener('change', (event) => {
            const input = event.target; 
            const reader = new FileReader(); 
            reader.onload = () => {
                list = reader.result.split(/\r?\n/);
                console.log(list)
            };
            reader.readAsText(input.files[0]);
        }) 
    });
}

const check = load_csv_async().catch((error) => {
console.log(error)});
console.log(check);
<!DOCTYPE html>
<meta charset="utf-8">
<input type="file" name="inputfile" id="inputfile">

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

It's a good idea to use promises and wrap the file reader with one. Your read function should invoke resolve when the file is loaded (and ought to invoke reject on error).

It also makes sense to tease apart triggering action and a generic async file reader that takes a file and returns a promise. Doing so will provide a natural place to get the contents, avoiding a global altogether...

const fileInput = document.querySelector('input');
fileInput.addEventListener('change', async (event) => {
  try {
    const fn = event.target.files[0];
    const text = await load_csv_async(fn);
    // text was global, now it's in a functional scope where it belongs
    console.log(text);
  } catch(err) {
    console.log(err);
  }
});
 
async function load_csv_async(fn){
  return new Promise((resolve,reject) => {
    const reader = new FileReader(); 
    reader.onload = () => {
      const list = reader.result.split(/\r?\n/);
      resolve(list);
    };
    reader.onerror = error => {
      reject(error)
    };
    reader.readAsText(fn);

  });
}
<!DOCTYPE html>
<meta charset="utf-8">
<input type="file" name="inputfile" id="inputfile">

about 4 years ago · Juan Pablo Isaza Denunciar

0

As far as i understood your question, you want the result of the csv upload to be handled by another function call. For this you do not need to wrap it inside a promise or async function, you can simply structure your program to call the functions inside the event handler:

fileInput.addEventListener('change', (event) => {
            const input = event.target; 
            const reader = new FileReader(); 
            reader.onload = () => {
                list = reader.result.split(/\r?\n/);
                console.log(list)
            };
            
            // if you want to have this as global variable just put it outside the Event Listener
            let result = reader.readAsText(input.files[0]);
            someOtherFunction(result)
            
}) 

function someOtherFunction(param) {
  console.log(param)
}
<!DOCTYPE html>
<meta charset="utf-8">
<input type="file" name="inputfile" id="inputfile">

Hint: If you use promise for anything: you have to call resolve on result and reject on error in order to handle it properly:

return new Promise((resolve, reject) => {
    result = SomeFunctionToGetYourResult();
    if (result=="SomeTargetValue") {
        // Resolve if result is as intended
        resolve(result)
    } else {
        // Reject if your call was unsuccesfull.
        reject(SomeError)
    }

})

Another option is to call an async function in javascript:

async function someAsyncFunc() {

  return someAsyncProcessedValue;

}

let global;

try {
  
  global = await someAsyncFunction();

} catch (error) {
   console.log(error)
}
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