【问题标题】:Node DynamoDB Request to object or Variable节点 DynamoDB 对对象或变量的请求
【发布时间】:2013-12-06 23:12:31
【问题描述】:

我是编码新手,所以答案可能是基本的。我希望将 (AWS.Request) describeTable(params = {}, callback) 回调中的 data 分配给一个变量。这样我就可以使用该变量有条件地检查属性。

app.get('/chat/:eventName', function(req, res){
  var tableName = req.params.eventName;
  var dataBaseName = dbDescribe(tableName);
  if (dataBaseName.Table.TableName == tableName) {
      console.log('Table Already Exists');
    } else {
      dbCreate(tableName);
      console.log('Table Created');
    };
});

function dbDescribe(tableName) {
  dynamodb.describeTable({TableName: tableName}, function (err, data) {
        if (err) {
          console.log('Status Code = ' + err.statusCode); // an error occurred
        } else {
          console.log('DATA COMING THRU');    
          console.log(data); // successful response
        };
    }
  );
};

我的目标是从回调函数中获取“数据”以在 else where 中使用,但是 dynamodb.describeTable 的常规输出与数据不同,它看起来像是为请求发送的所有信息的对象.

我仍然是初学者,所以可能只是我看错了,但我会被任何提示或帮助激怒。

第一次请求事件 URL 时,应用正在创建数据库表。然后,对于未来的连接,事件的信息将从现有表中提取,直到事件/表被删除。

【问题讨论】:

    标签: javascript node.js amazon-web-services callback amazon-dynamodb


    【解决方案1】:

    您必须使用回调,将 dbDescribe 中的结果(如果请求失败则返回错误)传递给您的方法。

    app.get('/chat/:eventName', function(req, res){
      var tableName = req.params.eventName;
      dbDescribe(tableName, function(err, dataBaseName) {
        if (dataBaseName.Table.TableName == tableName) {
          console.log('Table Already Exists');
        } else {
          dbCreate(tableName);
          console.log('Table Created');
        };
      }
    });
    
    var dbDescribe = function (tableName, cb) {
      dynamodb.describeTable({TableName: tableName}, function (err, data) {
          if (err) {
            console.log('Status Code = ' + err.statusCode); // an error occurred
            cb(err);
          } else {
            console.log('DATA COMING THRU');
            console.log(data); // successful response
            cb(null, data);
          };
        }
      );
    };
    

    您可以在此处获取有关回调的更多信息:

    http://www.nodebeginner.org/#event-driven-callbacks

    【讨论】:

    • 感谢您的回答和资源。这确实奏效了,我正在学习回调是如何工作的,并试图学习如何避免回调地狱。我想知道使用 Backbone 和 MVC 是否会是更好的方法?
    猜你喜欢
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多