¿Cómo puedo prometer el SDK de AWS JavaScript?


Quiero usar aws-sdk en JavaScript usando promises.

En lugar del estilo de devolución de llamada predeterminado:

dynamodb.getItem(params, function(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
});

En su lugar, quiero usar un estilo promise :

dynamoDb.putItemAsync(params).then(function(data) {
  console.log(data);           // successful response
}).catch(function(error) {
  console.log(err, err.stack); // an error occurred
});
Author: Jason, 2014-10-21

7 answers

Creo que las llamadas ahora se pueden agregar con .promise() para prometer el método dado.

Se puede ver que comienza a ser introducido en 2.6.12 https://github.com/aws/aws-sdk-js/blob/master/CHANGELOG.md#2612

Puede ver un ejemplo de su uso en el blog de AWS 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() ;
};
 3
Author: DefionsCode,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-11 19:17:35

La versión 2.3.0 del AWS JavaScript SDK agregó soporte para promises: http://aws.amazon.com/releasenotes/8589740860839559

 30
Author: Majix,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-01 00:31:05

Puede usar una biblioteca promise que haga promisificación, por ejemplo, Bluebird.

Aquí hay un ejemplo de cómo promisificar DynamoDB.

var Promise = require("bluebird");

var AWS = require('aws-sdk');
var dynamoDbConfig = {
  accessKeyId: process.env.AWS_ACCESS_KEY_ID,
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  region: process.env.AWS_REGION
};
var dynamoDb = new AWS.DynamoDB(dynamoDbConfig);
Promise.promisifyAll(Object.getPrototypeOf(dynamoDb));

No se puede agregar Async a cualquier método para obtener la versión prometida.

 24
Author: Martin Kretz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-20 21:47:24

Muy atrasado, pero hay un módulo npm aws-sdk-promise que simplifica esto.

Esto solo agrega una función promise() que se puede usar así:

ddb.getItem(params).promise().then(function(req) {
    var x = req.data.Item.someField;
});

EDIT: Han pasado algunos años desde que escribí esta respuesta, pero como parece estar recibiendo votos últimamente, pensé en actualizarla: aws-sdk-promise está en desuso, y las versiones más nuevas (como en, el último par de años) de aws-sdk incluyen soporte promise incorporado. La promesa de implementación a el uso se puede configurar a través de config.setPromisesDependency().

Por ejemplo, para que aws-sdk devuelva Q promesas, se puede usar la siguiente configuración:

const AWS = require('aws-sdk')
const Q = require('q')

AWS.config.setPromisesDependency(Q.Promise)

La función promise() devolverá Q promesas directamente (al usar aws-sdk-promise, tenía que envolver cada promesa devuelta manualmente, por ejemplo, con Q(...) para obtener Q promesas).

 12
Author: JHH,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-19 07:22:50

Amigos, No he podido usar el Promise.promisifyAll(Object.getPrototypeOf(dynamoDb));

Sin embargo, lo siguiente funcionó para mí:

this.DYNAMO = Promise.promisifyAll(new AWS.DynamoDB());
...
return this.DYNAMO.listTablesAsync().then(function (tables) {
    return tables;
});

O

var AWS = require('aws-sdk');
var S3 = Promise.promisifyAll(new AWS.S3());

return S3.putObjectAsync(params);
 4
Author: Cmag,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-25 21:48:11

CascadeEnergy / aws-prometido

Tenemos un módulo npm siempre en progreso aws-promised que hace la promesa bluebird de cada cliente del aws-sdk. No estoy seguro de que sea preferible usar el módulo aws-sdk-promise mencionado anteriormente, pero aquí está.

Necesitamos contribuciones, solo nos hemos tomado el tiempo para prometer los clientes que realmente usamos, pero hay mucho más que hacer, así que por favor hazlo!

 1
Author: nackjicholson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-17 04:46:26

Con async/await encontré el siguiente enfoque bastante limpio y solucioné el mismo problema para mí para DynamoDB. Esto también funciona con ElastiCache Redis. No requiere nada que no venga con la imagen lambda predeterminada.

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));
}
 1
Author: C.J.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-11 03:37:31