You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在AWS Lambda中调用AWS StepFunctions返回null无报错如何解决

问题根因与解决方案

核心根因

你使用了async声明Lambda处理程序,但内部的AWS SDK调用采用回调模式,没有等待异步操作执行完成:

  • async类型的Lambda处理程序会忽略传入的callback参数,仅会等待处理程序返回的Promise状态变更后再结束执行
  • 你的代码中没有返回任何Promise,也没有等待startSyncExecution的回调触发,Lambda在发起Step Function调用请求后就直接终止,因此回调内的日志、返回逻辑都不会执行,Step Function也没有实际收到执行请求,自然返回null。

解决方案

方案1:移除async关键字,使用回调模式

直接删除handler前的async声明即可,非async模式的Lambda会正常识别callback参数,等待回调触发后再结束执行:

const AWS = require('aws-sdk');

// 移除async关键字
exports.handler = (event, context, callback) => {
    var params = {
        stateMachineArn: "arn:aws:states:us-east-1:[AccountID]:stateMachine:BookLectureStateMachine",
        input: JSON.stringify(event),
        name: "test-from-lambda"
    }
    
    var stepfunctions = new AWS.StepFunctions();
    console.log("Everything okay");

    stepfunctions.startSyncExecution(params, function(err, data) {
        console.log("This log will now be shown");
        if (err) {
            callback(null, {
                statusCode: 400,
                body: err,
                headers: {
                    'Access-Control-Allow-Origin': '*'
                }
            })
        } else {
            callback(null, {
                statusCode: 200,
                body: 'Lecture booked',
                headers: {
                    'Access-Control-Allow-Origin': '*'
                }
            })
        }
    });
};

方案2:保留async,改用Promise化调用(更推荐)

使用AWS SDK的.promise()方法将调用转为Promise,配合await等待执行完成,代码逻辑更清晰:

const AWS = require('aws-sdk');
const stepfunctions = new AWS.StepFunctions();

exports.handler = async(event, context) => {
    var params = {
        stateMachineArn: "arn:aws:states:us-east-1:[AccountID]:stateMachine:BookLectureStateMachine",
        input: JSON.stringify(event),
        // 注意:执行名称必须全局唯一,固定值重复调用会报错,建议加入随机后缀或者时间戳
        name: `test-from-lambda-${Date.now()}`
    }

    try {
        const data = await stepfunctions.startSyncExecution(params).promise();
        console.log("Execution completed", data);
        return {
            statusCode: 200,
            body: 'Lecture booked',
            headers: {
                'Access-Control-Allow-Origin': '*'
            }
        };
    } catch (err) {
        console.error("Execution failed", err);
        return {
            statusCode: 400,
            body: err,
            headers: {
                'Access-Control-Allow-Origin': '*'
            }
        };
    }
};

额外注意事项

  • Step Function执行名称name参数必须唯一,固定值重复调用会触发报错,建议拼接时间戳、请求ID等唯一标识
  • 确认stateMachineArn中的[AccountID]已替换为实际的AWS账号ID,且Step Function所在区域与Lambda一致
  • 可在CloudWatch中查看Lambda的完整执行日志,排查调用返回后的具体错误信息

内容的提问来源于stack exchange,提问作者Francesco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 01:24:03