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

82
Visualizações
JS await function with empty Promise

I have a question, I somewhat understand how Promises work but I would like to wait for a function to finish even if it doesn't return anything. I have a similar code but it doesn't wait for b to finish before starting the extra steps on a.

For example in this case I want to create tables in a sqlite db, then load data and run some tests. The thing here is that it's starting to run the tests before finishing to load the data and the arrays created in the loadData method are coming empty. I would even prefer not to return those arrays but to always wait for this process to be completed before running tests.

async function initialize(){
    try{
        console.log("Beginning connection");
        db = await connectToDB();
        console.log(`Database: ${db}`)
        db.serialize(function() {
            console.log("Creating tables")
            db.run(queries.__parent_company);
            db.run(queries.parent_company);
            db.run(queries.__sales_rep);
            db.run(queries.sales_rep);
            db.run(queries.advertiser);
            console.log("Tables created");
        });
        let response = await loadData();
        console.log("Response", response)
        testData();
    }
    catch(e){
        throw e;
    }
}

function loadData() {
    return new Promise(async (resolve, reject) => {
        console.log("Beggning data insertion");
        try{
            let insertedAdvertisers = [];
            let insertedSales = [];
            let insertedCOmpanies = [];
            data.rows.forEach(async row => {
                let advertiser = await loadAdvertisers(row);
                let sale = await loadSalesRep(row);
                let company = await loadParentCompany(row);
                insertedAdvertisers.push(advertiser);
                insertedSales.push(sale);
                insertedCOmpanies.push(company);
                console.log("HERE", insertedAdvertisers, insertedSales, insertedCOmpanies)
            })
            resolve({insertedAdvertisers, insertedSales, insertedCOmpanies});
        }
        catch(e){
            console.log(e);
            reject(e);
        }
    });
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Taking about Promises, I advice you to read about the event loop and how it works.

What happens in your code that JS knows that this is a promise so it will move it to callback queue until it finishes and continues executing your code and then push it to the stack to be executed. so if you want to execute a certain logic after an async function finishes you need to provide it as a callback or use .then()

async function a() {
  b().then(()=>{
      // your code that you want to be executed after a finishes 
})
}

This image might illustrate what I'm trying to explain

enter image description here

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