如何让lambda等待回调?

How to make lambda wait for callback?

我正在创建一个 AWS lambda 函数,它应该定期备份 S3 上的 AppSync API(它由 CloudWatch 计划规则触发)。 它基于 class,对于作为函数参数传递的每个 API(使用环境变量)运行s API.[=22 的每个元素的备份作业=]

如果我 运行 它只使用节点,它可以正常工作。

但是,当我使用无服务器框架(serverless deployserverless invoke local -f backup)在本地部署或测试时,执行在处理函数以外的范围内的第一条异步指令处停止,我是否使用回调、Promise.then() 或 async/await 语法。

我已经考虑过,运行为备份操作的每个部分使用多个 lambda 函数,但是这样我会丢失共享上下文,我需要它来确保备份的每个部分都正确完成.

handler.js

  // for testing purposes
    // works, waits 5 seconds and execute the rest of the code
    console.log("here1");
    await new Promise(resolve => setTimeout(resolve, 5000));
    console.log("here2");
    const allBackups = apiIds.map(apiId => new Backup(apiId));
    allBackups.map(backup => backup.start());

Result => here1
[5 seconds wait]
here2

但是,如果我调用一个使用异步代码的函数,例如 Backup class 的 start 方法(在所需的 Backup.js 文件中) ,会发生以下情况:



async start() {
        try {
            console.log("here3");
            const data = await this.AppSync.getGraphqlApi({ apiId: this.apiId }).promise();
            console.log("here4");

Result => here1
[5 seconds wait]
here2
here3
End of execution

我拥有所有必需的角色,无服务器报告在本地部署或调用时没有问题。

这是我的 serverless.yml 文件:

service:  [name]

provider:
  name: aws
  runtime: nodejs8.10

functions:
  backup:
    handler: handler.backup
    environment:
     [env variables, they are parsed properly]
    timeout: 60
    event:
      schedule: [doesn't work as well, but it's not the issue here]
        name: daily-appsync-backup
        rate: cron(0 0 ** ? *)
        enabled: false
    role: [role]

在此先感谢您的帮助!

好的,所以我找到了解决方案,我就是这样做的:

    const allBackups = apiIds.map(apiId => new Backup(apiId));
    await Promise.all(allBackups.map(async backup => backup.start()));

它没有工作,因为它到达了处理程序函数的末尾并且不关心是否还有其他回调在等待。 (我还了解到您可以 await 一个 async 函数,而不仅仅是一个 Promise。)