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

214
Visualizações
Need Help : How do I resolve this function?
const getDbInfo = (anArrayOfIDs) => {
    return new Promise(function(resolve, reject){
        let arrayOfDbInfoToSendBack = [];
        for(let i = 0; i <= anArrayOfIDs.length-1; i++){
            pool.query(
                "SELECT * FROM `tbl_ofInfo` WHERE tbl_ofInfo.sqlID = '" +
                anArrayOfIDs[i] +
            "';",
            async(err, res) => {
                if (err) {
                    console.log("error: ", err);
                  } else {
                      for(let k = 0; k <= res.length-1; k++){
                         arrayOfDbInfoToSendBack.push(res);
                          
                      }
                      resolve(arrayOfDbInfoToSendBack);
                      
                  }
            }
            );
            
        }
    });
}

Expected this function to return an array of objects with information. I suspect I am using resolve incorrectly and it sending back an array of only 1 object when I want an array of multiple objects in it.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

In SQL every query is a promise, so there is no need to query inside a promise. To simplify the resolve, you can use async/await.

//Setting function asynchronous
const getDbInfo = async (anArrayOfIDs) => { 
    let arrayOfDbInfoToSendBack = [];
    for(let i = 0; i <= anArrayOfIDs.length-1; i++){
       let query = "SELECT * FROM `tbl_ofInfo` WHERE tbl_ofInfo.sqlID = '" + anArrayOfIDs[i] + "';"

       //Awaiting until the sql query resolved or rejected
       await pool.query(query,(err, res)=>{
           if (err) console.error(err)
           else {
               for(let k = 0; k <= res.length-1; k++){
                   arrayOfDbInfoToSendBack.push(res);
           }
       })
    }
}

Btw, I'm not sure this function will work if you declare it outside your route. Because Nodejs will try to execute it once the server is up and fails for the reason it cannot find an argument of anArrayOfIDs. So, use the function inside your route. If you have to use it often, move your function to a different .js file, export it from there and then import it as middleware to where you want to use it.

about 4 years ago · Juan Pablo Isaza Relatório

0

Does this piece of code work?

const getDbInfo = (anArrayOfIDs) => {
  return new Promise(function(resolve, reject) {
    pool.query("SELECT * FROM `tbl_ofInfo` WHERE tbl_ofInfo.sqlID IN (?)", anArrayOfIDs ,
      (err, res) => {
          if (err) {
          console.log("error: ", err);
          reject(err);
          return;
        } 

        resolve(res)        
      }
    );       
  });
}
about 4 years ago · Juan Pablo Isaza Relatório

0

If the one object that is being returned is correct one, then problem can be rooted back to the fact that you are resolving inside the for loop. That means that only first iteration is called and then as promise has already resolved then next iterations are obsolete considering the callback nature of pool.query i would assume that putting await before it can solve the problem

const getDbInfo = (anArrayOfIDs) => {
    return new Promise(async function (resolve, reject) {
        let arrayOfDbInfoToSendBack = [];
        anArrayOfIDs.forEach(async (id) => {
            await pool.query(
                "SELECT * FROM `tbl_ofInfo` WHERE tbl_ofInfo.sqlID = '" +
                id +
                "';",
                async (err, res) => {
                    if (err) {
                        console.log("error: ", err);
                    } else {
                        for (let k = 0; k <= res.length - 1; k++) {
                            arrayOfDbInfoToSendBack.push(res);

                        }


                    }
                }
            );
            resolve(arrayOfDbInfoToSendBack);
        });
    });
}
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