如何在 DynamoDB 中使用 node.js 个生成器

How to use node.js generators with DynamoDB

我正在尝试使用生成器从我的本地 dynamoDB 中放入和获取数据。到目前为止,我的代码 returns 相当大的对象。但我不太确定我是否真的与数据库进行了交互。如果是这样,我不知道如何实际检索数据。 另一件事是不使用生成器时需要的回调函数。我应该把它留在外面吗?如果不是,我将如何将结果提供给 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 不能 return 值。最佳做法是 return 所谓的承诺。 一旦值可用,调用函数就可以使用它。生成器可以让代码看起来更漂亮,更易读。