Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

93
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda