【问题标题】:Scheduled Lambda function not able to make 3rd party API calls计划的 Lambda 函数无法进行第 3 方 API 调用
【发布时间】:2019-01-15 05:30:02
【问题描述】:

我有 3 个函数。

  1. Cron 作业 lambda 函数
  2. 事件驱动函数,用于检测何时将新记录添加到 DynamoDB 中
  3. 当前由上述 2 个函数调用的可重用函数

Cron 作业函数

export async function scheduledFunction() {
    const detailsHistory = await sharedFunction(param1);
}

事件驱动函数

export async function eventFunction(event) {
    event.Records.forEach(async record => {
        if (record.eventName === 'INSERT') {
            await sharedFunction(param1)
        }
    }
}

事件和调度函数都调用的函数

const sharedFunction = async (param1) {
    const apiUrl = 'xxxxxx';
    const details = await axios.get(apiUrl, {
        headers: {
            'x-api-key': xxxx
        }
    }); 
}

DynamoDB 有一个新插入然后调用按预期工作的第 3 方 API 时,事件函数起作用

计划的函数每 4 小时触发一次,并且可以正常工作并到达 sharedFunction,但是当它到达 API 调用 await axios.get 时,它什么也不做,我在 CloudWatch 中没有收到任何错误。我在通话前后放置了console.logs(),它记录了之前的,但之后没有。

【问题讨论】:

    标签: aws-lambda serverless-framework serverless


    【解决方案1】:

    您应该始终将异步代码放在 try ... catch 块中。此外,forEach 将无法与您需要使用 for 循环的承诺一起使用。试试这个:

    export async function eventFunction(event) {
      try {
    
        for (let record of event.Records) {
          if (record.eventName === 'INSERT') {    
            await sharedFunction(param1)
          }
        }
      }
      catch (err) {
        console.log(err);
        return err;
      }
    }
    

    共享功能:

    const sharedFunction = async (param1) => {
      try {
        const apiUrl = 'xxxxxx';
        return await axios.get(apiUrl, {
            headers: {
                'x-api-key': xxxx
            }
        });
    
      }
      catch (err) {
        return err;   
      } 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-29
      • 1970-01-01
      • 2019-04-08
      • 1970-01-01
      • 2017-09-03
      • 1970-01-01
      • 2017-09-29
      相关资源
      最近更新 更多