[英]How to use node.js generators with DynamoDB
我正在尝试使用生成器从本地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();
*/
我发现我想做的事是不可能的。 通过I / O操作检索其值的getter无法返回值。 最佳实践是返回所谓的promise。 值可用后,调用函数即可使用它。 生成器可以使代码看起来更漂亮,更易于阅读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.