首页 > 解决方案 > 关于 AWS Lambda RDS + dynamoDB 在同一个函数中查询的基本 JS 问题

问题描述

我从 AWS 服务开始,我有一个关于 Lambda 函数的问题。我想编写一个同时使用 RDS 和 dynamoDB 的函数。我写了一个简单的函数来查询 RDS,它工作正常。然后,我做的第一件事是创建一个响应数组,它将是整个响应(这里我想从数据库中放入两个响应对象)。然后我将成功回调移到 de MySQL 查询之外,因为该函数在那一点没有结束,我想在调用 dynamoDB 并将其响应对象推送到数组之后调用回调。但是当我这样做并测试功能时,响应只是空的。你能帮我解决这个问题吗?我认为这是一个愚蠢的错误,但我不明白:(

exports.handler = (event, context, callback) => {
  let sendResult = [];
  //prevent timeout from waiting event loop
  context.callbackWaitsForEmptyEventLoop = false;
  const query = `SELECT * from Users`;
   pool.query(query, (error, results) => {
     sendResult.push(results[0]); // Insert the result in response object
     if (error) callback(error);
     // else callback(null, sendResult); 
     // I remove the callback from here because after this query I want something from dynamoDB
  });
  ////////////////////////////////
  // Here I put the dynamoDB query and add the response object to sendResult before calling callback
////////////////////////////////
  callback(null, sendResult); // At this point, this should contain RDS object but it doesn't and the Result is [] :(
};

代码

标签: javascriptamazon-web-servicesaws-lambdaamazon-dynamodbclosures

解决方案


推荐阅读