[英]AWS Dynamodb not fetching data synchronously by node js
我是node js dynamo db的新手,我寫了一個node js sdk來從表dynamodb上獲取一行。 它正在正確獲取數據,但不是立即獲取此錯誤
我的代碼在一個簡單的代碼下面
var AWS = require("aws-sdk");
var config = function(){
AWS.config.update({region: 'us-east-1'});
// Create the DynamoDB service object
var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'});
var params = {
TableName: 'tblConfigs',
// Key: {
// "id" : {S: "1"},
// }
ExpressionAttributeValues: {
":v1": {
S: "1"
}
},
FilterExpression: "id = :v1",
};
var v;
var json = ddb.scan(params, function(err, data) {
if (err) {
console.log("Error", err);
} else {
v = data;
// console.log(JSON.stringify(data.Item));
// return JSON.stringify(data.Item);
}
});
// if(v=="u")
// for(var i=0;)
v = v.Items[0];
// for()
var con = {
"host": v.endpoint.S,
"user": v.endpoint.username.S,
"password": v.endpoint.password.S,
"database": v.endpoint.database_name.S
};
return con;
}
我得到了以下錯誤
> config()
TypeError: Cannot read property 'Items' of undefined
at config (repl:31:7)
由於v是未定義的,所以它給出了錯誤,但是當我在節點控制台中執行代碼時v不是未定義的,它是第一次給出undefined,下次是給出值
像下面
> v
{ Items:
[ { password: [Object],
stage: [Object],
username: [Object],
id: [Object],
endpoint: [Object],
database_name: [Object] } ],
Count: 1,
ScannedCount: 1 }
一段時間后如何立即獲取行? 我嘗試過的dynamodb中有什么好方法嗎,get,getItem,掃描,查詢都正確地提供了數據但不是立即...請建議
您缺少一件事:Java語言執行是異步的。 只要您不使用async/await
語法,就必須像下面這樣“播放”回調:
var ddb = new AWS.DynamoDB({ apiVersion: '2012-08-10' });
function loadConfig(callback) {
var params = {
TableName: 'tblConfigs',
ExpressionAttributeValues: {
':v1': {
S: '1'
}
},
FilterExpression: 'id = :v1'
};
ddb.scan(params, function (error, data) {
if (error) {
callback(error);
} else {
var item = data.Items[0];
callback(null, {
'host': item.endpoint.S,
'user': item.endpoint.username.S,
'password': item.endpoint.password.S,
'database': item.endpoint.database_name.S
});
}
});
}
loadConfig(function (error, configuration) {
if (error) {
console.log(error);
} else {
// Your connection logic (JUST AN EXAMPLE!)
var connection = mysql.connect({
host: configuration.host,
user: configuration.user,
password: configuration.password,
database: configuration.database
})
}
});
順便說一句。 在DynamoDB中存儲數據庫配置不是一個好的解決方案,我建議您檢查AWS Systems Manager Parameter Store
。
編輯
給你一個簡短的例子, async/await
語法看起來像
var ddb = new AWS.DynamoDB({ apiVersion: '2012-08-10' });
const loadConfig = async () => {
const { Items } = await ddb.scan({
TableName: 'tblConfigs',
ExpressionAttributeValues: {
':v1': {
S: '1'
}
},
FilterExpression: 'id = :v1'
}).promise();
const item = Items[0];
return {
'host': item.endpoint.S,
'user': item.endpoint.username.S,
'password': item.endpoint.password.S,
'database': item.endpoint.database_name.S
};
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.