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

78
Visualizações
Lambda is not waiting for Async/Await

Lamda ends the process and it's not waiting for the API response. here is my code:

exports.handler = async (event, context, cb) => {

 try {
    console.log('FETCHING RECORDS FROM DATOCMS')
    const allItems = await client.items.all({}, { allPages: true })
    if (!fs.existsSync(backupDir)){
        // Create backup directory
        console.log('CRETING BACKUP DIRECTORY')
        fs.mkdirSync(backupDir, { recursive: true });
    }

    console.log('FILL JSON WITH RECORDS FETCHED FROM DATOCMS')
    fs.writeFileSync('backup/records.json', JSON.stringify(allItems, null, 2));

    console.log('ADDING BACKUP FOLDER TO ZIP')
    zip.addLocalFolder(backupDir);
    const zipFileContents = zip.toBuffer();
    
    const params = {
        Bucket: S3_BUCKET,
        Key: `backup_zip-${backupDate}`,
        Body: zipFileContents,
        ContentType: "application/zip",
        ContentDisposition: `attachment; filename="${fileName}-${backupDate}"`
    }

    console.log('UPLOADING ZIP TO S3', params)
    s3.putObject(params, (err, data) => {
        if (err) {
            cb(null, 'Error')
            throw new Error('The zip file could not be uploaded', err);
        }
        console.log('Uploaded correctly')
        cb(null, 'Success')
        fs.rmdirSync(backupDir, { recursive: true });
    })
 } catch (err) {
    cb(null, 'Error..')
    throw new Error('An error occurred', err)
 }
}

I also tried adding this two lines with no luck

 setInterval(() => {}, 1000);
 context.callbackWaitsForEmptyEventLoop = false;

Can anyone help me? I've been testing Promises, Async/Await, Callbacks and no luck with that. Thanks!

This is the response in CloudWatch

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

0

Try to map the promises, then await on Promise.all. I'm not sure if all returns array of promises.

const promises =  client.items.map(it=>...)
const promises =  client.items.all(it=>...)
await Promise.all(promises)
about 4 years ago · Juan Pablo Isaza Relatório

0

You aren't waiting for s3.putObject. It should be:

const data = s3.putObject(params).promise();

You handle the error in a try/catch.

about 4 years ago · Juan Pablo Isaza Relatório

0

Remove the async keyword from the handler. You can't use the callback function in the async/await function.

Try to use the aws sdk function with .promise();

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