【问题标题】:Lambda is not waiting for Async/AwaitLambda 不等待 Async/Await
【发布时间】:2021-12-11 17:43:13
【问题描述】:

Lamda 结束进程并且它不等待 API 响应。这是我的代码:

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)
 }
}

我也尝试添加这两行,但没有成功

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

谁能帮帮我? 我一直在测试 Promises、Async/Await、Callbacks,但没有运气。谢谢!

This is the response in CloudWatch

【问题讨论】:

    标签: javascript node.js amazon-web-services aws-lambda


    【解决方案1】:

    尝试映射承诺,然后将await 映射到Promise.all。我不确定all 是否返回承诺数组。

    const promises =  client.items.map(it=>...)
    const promises =  client.items.all(it=>...)
    await Promise.all(promises)
    

    【讨论】:

      【解决方案2】:

      您无需等待s3.putObject。应该是:

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

      您在 try/catch 中处理错误。

      【讨论】:

      • 我这样做了,但问题出在 await 调用上,我需要将数据打包成一个 zip 然后上传到 S3
      【解决方案3】:

      从处理程序中删除 async 关键字。不能在 async/await 函数中使用回调函数。

      尝试使用带有.promise();的aws sdk功能

      【讨论】:

      • 我这样做了,但问题在于等待调用
      【解决方案4】:

      为了更容易理解,您可以使用回调样式 (handler = (event, context, callback) => {})) 或承诺样式 (handler = async (event, context))。不要将两者结合起来。

      exports.handler = async (event, context) => {
          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);
              // We switch this to use a promise.
              await s3.putObject(params).promise();
              fs.rmdirSync(backupDir, {recursive: true});
          } catch (err) {
              throw new Error('An error occurred', err);
          }
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-03-08
        • 1970-01-01
        • 2020-08-03
        • 2021-01-26
        • 2019-04-14
        • 2018-09-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多