AWS AppSync查询返回null但Lambda已有结果的问题求助
问题排查与修复
核心问题:Lambda异步处理未正确等待
你的Lambda函数中,client.request是异步Promise操作,但你没有等待它完成就直接返回response变量。此时response还未被赋值(初始状态为undefined),导致Lambda实际返回undefined,AppSync解析后就会返回null。
同时,第三方API返回的数据结构是{events: {nodes: [...]}},而你的Schema中events字段需要返回EventsConnection类型(包含nodes和totalCount),需要确保返回的结构匹配Schema要求。
修复步骤
1. 修正Lambda异步逻辑
将Lambda函数改为异步函数,使用await等待API请求完成,确保返回正确的数据:
const client = new GraphQLClient(eventsGraphQLURI, { headers: {} }) exports.handler = async (event) => { try { const data = await client.request(request); console.log(`Result: ${JSON.stringify(data)}`); // 提取第三方API返回的events数据,匹配EventsConnection结构 return { nodes: data.events.nodes, totalCount: data.events.nodes.length }; } catch (error) { console.log(`Error Occurred: ${error}`); throw new Error(error); } };
2. 确保数据结构匹配Schema
你的EventsConnection类型要求必须包含nodes和totalCount字段,Lambda返回的对象必须同时提供这两个字段。如果第三方API没有返回totalCount,可以通过nodes数组的长度生成。
3. 验证映射模板正确性
你的请求映射模板已硬编码测试,无需调整;响应模板$util.toJson($context.result)逻辑正确,只要Lambda返回符合Schema的结构,AppSync就能正常解析。
额外检查点
- 确认Lambda执行角色拥有被AppSync调用的权限,且Lambda本身能正常访问第三方API
- 查看AppSync的CloudWatch日志,验证Lambda返回值是否为
undefined或不符合Schema的结构 - 核对Schema中
events字段的返回类型确实是EventsConnection,无类型不匹配问题
内容的提问来源于stack exchange,提问作者Sivvie Lim
相关产品推荐
相关产品推荐

