How do I promisify the AWS JavaScript SDK?

后端 未结 8 1081
面向向阳花
面向向阳花 2020-12-08 18:52

I want to use the aws-sdk in JavaScript using promises.

Instead of the default callback style:

dynamodb.getItem(params, function(err, data) {
  if (         


        
相关标签:
8条回答
  • 2020-12-08 19:28

    I believe calls can now be appended with .promise() to promisify the given method.

    You can see it start being introduced in 2.6.12 https://github.com/aws/aws-sdk-js/blob/master/CHANGELOG.md#2612

    You can see an example of it's use in AWS' blog https://aws.amazon.com/blogs/compute/node-js-8-10-runtime-now-available-in-aws-lambda/

    let AWS = require('aws-sdk');
    let lambda = new AWS.Lambda();
    
    exports.handler = async (event) => {
        return await lambda.getAccountSettings().promise() ;
    };
    
    0 讨论(0)
  • 2020-12-08 19:29

    With async/await I found the following approach to be pretty clean and fixed that same issue for me for DynamoDB. This works with ElastiCache Redis as well. Doesn't require anything that doesn't come with the default lambda image.

    const {promisify} = require('util');
    const AWS = require("aws-sdk");
    const dynamoDB = new AWS.DynamoDB.DocumentClient();
    const dynamoDBGetAsync = promisify(dynamoDB.get).bind(dynamoDB);
    
    exports.handler = async (event) => {
      let userId="123";
      let params =     {
          TableName: "mytable",
          Key:{
              "PK": "user-"+userId,
              "SK": "user-perms-"+userId
          }
      };
    
      console.log("Getting user permissions from DynamoDB for " + userId + " with parms=" + JSON.stringify(params));
      let result= await dynamoDBGetAsync(params);
      console.log("Got value: " + JSON.stringify(result));
    }
    
    0 讨论(0)
提交回复
热议问题