2016-06-26 3 views
0

발전기를 사용하여 로컬 DynamoDB에서 데이터를 가져오고 가져 오는 중입니다. 지금까지 제 코드는 꽤 큰 객체를 반환합니다. 하지만 실제로 데이터베이스와 상호 작용하는지는 잘 모르겠습니다. 그렇다면 실제로 데이터를 검색하는 방법을 알 수 없습니다. 또 다른 것은 생성기를 사용하지 않을 때 필요한 콜백 함수입니다. 나는 그것을 버려야 하나? 그렇지 않다면 next() 함수에 결과를 어떻게 전달할 것인가?DynamoDB에서 node.js 생성기를 사용하는 방법

도움을 주시면 감사하겠습니다. :-)

지금까지 내 코드는 다음과 같습니다

'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

나는 내가하고 싶은 것은 불가능하다는 것을 알게되었습니다. 입출력 조작에 의해 그 값을 취득하는 취득 메소드는 값을 돌려 줄 수 없습니다. 가장 좋은 방법은 약속이라고하는 것입니다. 값을 사용할 수있게되는 즉시 호출 함수에서 사용할 수 있습니다. 생성기를 사용하면 코드를 더 아름답고보기 쉽게 만들 수 있습니다.

관련 문제