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

本地运行Lambda无法输出回调函数内console.log日志该如何解决

问题根本原因

你当前混用了async异步函数声明和回调式API,AWS Lambda的async处理机制会在顶层同步代码执行完成后直接终止运行环境,不会等待SNS.publish的回调逻辑执行,因此回调内的日志没有机会输出。
本地运行时Node.js进程会默认等待事件循环中的所有回调执行完成再退出,所以本地运行功能正常,和云端Lambda的运行机制存在差异。

修复方案

有两种可行的修复方式:

方式1(推荐):适配async函数,用Promise + await写法

AWS SDK v2的所有API都支持.promise()方法转成Promise调用,配合await等待执行完成后再结束函数:

const AWS = require('aws-sdk');
exports.lambdaHandler = async (event, context) => {
    console.log("START v5");
    const SNSarn = process.env.SNS;
    console.log(SNSarn);
    const snsParams={
        Message: "test",
        TopicArn: SNSarn
    };
    const SNS = new AWS.SNS();
    try {
        // 等待publish执行完成
        const publishRes = await SNS.publish(snsParams).promise();
        console.log("We are in the callback!");
        console.log('Sent message, response:', publishRes);
        console.log('END');
        return "Done!";
    } catch (err) {
        console.log('Error sending a message', err);
        throw err;
    }
};

方式2:移除handler的async声明,保留回调写法

如果要保留原有的回调和context.done写法,只需要去掉handler前的async修饰符即可,Lambda会等待context.done被调用后才终止函数执行:

const AWS = require('aws-sdk');
// 移除async关键词
exports.lambdaHandler = (event, context) => {
    console.log("START v5");
    const SNSarn = process.env.SNS;
    console.log(SNSarn);
    const snsParams={
        Message: "test",
        TopicArn: SNSarn
    };
    const SNS = new AWS.SNS();
    SNS.publish(snsParams, function(err,data){
        console.log ("We are in the callback!");
        if (err) {
            console.log('Error sending a message', err);
            context.done(err,'We have errors');
        }
        console.log('Sent message');
        context.done(null,"Done!");
    });
    console.log('END');
};

内容的提问来源于stack exchange,提问作者Itay Moav -Malimovka

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 05:54:05