我正在尝试使用生成器从本地dynamoDB中获取和获取数据。到目前为止,我的代码返回了很大的对象。但我不确定我是否真的与数据库交互。如果是这样,我无法弄清楚如何实际检索数据。 另一件事是不使用生成器时需要的回调函数。我应该把它留下吗?如果没有,我将如何将结果产生到next() - 函数?
非常感谢任何帮助! : - )
到目前为止,我的代码看起来像这样:
'use strict';
var AWS = require('aws-sdk');
AWS.config.update({accessKeyId: 'akid', secretAccessKey: 'secret'});
AWS.config.update({region: 'us-west-1'});
AWS.config.apiVersion = '2015-10-01';
//Using DynamoDB Local
var dyn = new AWS.DynamoDB({ endpoint: new AWS.Endpoint('http://localhost:8000') });
//Wrap the async calls in a generator functions
function* putItemGenerator(putParams) {
yield dyn.putItem(putParams);
}
function* getItemGenerator(getParams) {
yield dyn.getItem(getParams);
}
class User {
//The constructor creates a new user in the
//database and inserts his ID and name
constructor (args) {
this.userId = args.userId;
this.name = args.name;
let putParams = {
"TableName": "Users",
"Item": {
userId: { S: this.userId },
name: { S: this.name }
}
};
//Greate a generator and run it.
let result = putItemGenerator(dyn, putParams).next();
console.log(" === PUT RESULT === ");
console.log(result.value);
}
//Get the User from the Database
getUser() {
var getParams = {
"TableName": "Users",
"ConsistentRead": true,
"Key": {
"userId": { S: this.userId },
}
};
let result = getItemGenerator(dyn, getParams).next();
console.log(" === GET RESULT === ");
console.log(result.value);
return result.value;
}
}
var user = new User( {
userId: "1337",
name: "John Doe"
} );
user.getUser();
/*
//I created the table with this script.
'use strict';
var AWS = require('aws-sdk');
var createTables = function() {
AWS.config.update({accessKeyId: 'akid', secretAccessKey: 'secret'});
AWS.config.update({region: 'us-west-1'});
AWS.config.apiVersion = '2015-10-01';
let dyn = new AWS.DynamoDB({ endpoint: new AWS.Endpoint('http://localhost:8000') });
params = {
TableName : "Users",
KeySchema: [
{ AttributeName: "userId", KeyType: "HASH" }
],
AttributeDefinitions: [
{ AttributeName: "userId", AttributeType: "S" }
],
ProvisionedThroughput: {
ReadCapacityUnits: 1,
WriteCapacityUnits: 1
}
};
dyn.createTable(params, function(err, data) {
if (err)
console.log(JSON.stringify(err, null, 2));
else
console.log(JSON.stringify(data, null, 2));
});
}
createTables();
*/
答案 0 :(得分:0)
我发现我想做的事是不可能的。通过I / O操作检索其值的getter无法返回值。最好的做法是返回一个所谓的承诺。 一旦值可用,调用函数就可以使用它。生成器可以使代码看起来更漂亮,更容易阅读。