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

297
Visualizações
how to make sure callback of one function call, gets executed only after callback of the second function call

I am trying to parse a pdf containing data in the form of a table using javascript. My pdf file is a university time table in the form of a grid which has data in each grid. I am making use of pdfreader npm package(I am quite new to javascript so I am not sure if a better package exists for the usecase)

My plan is first parse through the pdf and with the help of few words I know are present in time table(eg name of days) and fetch the approximate x and y cordinates of the grid in the pdf. Secondly Parse throgh the pdf once again and now from the text I get populate some 2d array with the help of cordinates I fetched in first pass.

In the sample for pdf parser there is a function, parseFileItems which calls itemHandler(error, item) on each item parsed from the pdf file. So for the first pass I call the function like

  new PdfReader().parseFileItems("./timetable.pdf", (err, item) => {
    if (err) console.error("error:", err);
    else if (!item) console.warn("end of file");
    else if (item.text) {
        
        cordinatesofGrid=//my logic to fetch the cordinates of the grid
    }
  });

Now what I need to do is to parse through the pdf once again and make use of the "cordinatesofGrid" variable I have fetched in the first pass. so I again intend to call parseFileItems second time. But this should happen only once the first pass and its callback code is done executing.

I tried to call the first parseFileItems with await and then call parse function second time but this is not working as expected. (I assume this is because the wait does not apply to the callback)

  await new PdfReader().parseFileItems("./timetable.pdf", (err, item) => {
    //first call 
  });
  
  new PdfReader().parseFileItems("./timetable.pdf", (err, item) => {
    //second  call 
  });
  

Could anybody suggest how to make sure callback of one fucntion call, gets executed only after callback of the second function call

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You could create a Promise wrapper around the new PdfReader()

Quick FYI don't know if the pdf library is promise based! this is from the information you provided!

//This code will always resolve and never throw a reject
const PdfReaderAsync = () => {
    return new Promise((res, rej) => {
        new PdfReader().parseFileItems("./timetable.pdf", (err, item) => {
                if (err || !item) rej(err)
                res(item)
        })
    })
}

//Make the function you are calling this code async

//So you can use it like this
try {
    let item = await PdfReaderAsync()
    // Run through your code
} catch (err) {
    //handleError
}
// Code 2
try {
    let item = await PdfReaderAsync()
    // Run through your code
} catch (err) {
    //handleError
}

over 4 years ago · Santiago Trujillo Relatório

0

You could try using .then() function for promise handling.

Here's a LINK to some documentation on how it works/how to use it. I believe this would only work if your functions use promises (which I assumed since you tried awaiting).

over 4 years ago · Santiago Trujillo Relatório

0

You could put the second one in first callback and use await

  await new PdfReader().parseFileItems("./timetable.pdf", async(err, item) => {
      await new PdfReader().parseFileItems("./timetable.pdf", (err, item) => {
        //second  call 
      });
    //first call 
  });
  
over 4 years ago · Santiago Trujillo 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