node.js 我如何承诺 AWS JavaScript 开发工具包?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26475486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I promisify the AWS JavaScript SDK?
提问by Martin Kretz
I want to use the aws-sdk in JavaScript using promises.
我想通过 promise 在 JavaScript 中使用 aws-sdk。
Instead of the default callback style:
而不是默认的回调样式:
dynamodb.getItem(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
I instead want to use a promisestyle:
相反,我想使用承诺风格:
dynamoDb.putItemAsync(params).then(function(data) {
console.log(data); // successful response
}).catch(function(error) {
console.log(err, err.stack); // an error occurred
});
采纳答案by DefionsCode
I believe calls can now be appended with .promise()to promisify the given method.
我相信现在可以附加调用.promise()来保证给定的方法。
You can see it start being introduced in 2.6.12 https://github.com/aws/aws-sdk-js/blob/master/CHANGELOG.md#2612
你可以看到它在 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/
您可以在 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() ;
};
回答by Majix
The 2.3.0 release of the AWS JavaScript SDK added support for promises: http://aws.amazon.com/releasenotes/8589740860839559
AWS JavaScript SDK 的 2.3.0 版本增加了对 promise 的支持:http: //aws.amazon.com/releasenotes/8589740860839559
回答by Martin Kretz
You can use a promise library that does promisification, e.g. Bluebird.
您可以使用一个承诺库,做promisification,如蓝鸟。
Here is an example of how to promisify DynamoDB.
以下是如何承诺 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));
Not you can add Asyncto any method to get the promisified version.
不是你可以添加Async到任何方法来获得promisified 版本。
回答by JHH
Way overdue, but there is a aws-sdk-promisenpm module that simplifies this.
方式过期了,但有一个aws-sdk-promisenpm 模块可以简化这一点。
This just adds a promise() function which can be used like this:
这只是添加了一个 promise() 函数,可以像这样使用:
ddb.getItem(params).promise().then(function(req) {
var x = req.data.Item.someField;
});
EDIT: It's been a few years since I wrote this answer, but since it seems to be getting up-votes lately, I thought I'd update it: aws-sdk-promiseis deprecated, and newer (as in, the last couple of years) versions of aws-sdk includes built-in promise support. The promise implementation to use can be configured through config.setPromisesDependency().
编辑:我写这个答案已经有几年了,但由于它最近似乎得到了投票,我想我会更新它:aws-sdk-promise已弃用,更新的(如过去几年)版本aws-sdk 包括内置的承诺支持。要使用的承诺实现可以通过config.setPromisesDependency().
For example, to have aws-sdkreturn Qpromises, the following configuration can be used:
例如,要获得aws-sdk返回Q承诺,可以使用以下配置:
const AWS = require('aws-sdk')
const Q = require('q')
AWS.config.setPromisesDependency(Q.Promise)
The promise()function will then return Qpromises directly (when using aws-sdk-promise, you had to wrap each returned promise manually, e.g. with Q(...)to get Qpromises).
promise()然后该函数将Q直接返回承诺(使用 时aws-sdk-promise,您必须手动包装每个返回的承诺,例如使用Q(...)以获得Q承诺)。
回答by C.J.
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.
使用 async/await,我发现以下方法非常干净,并且为我解决了 DynamoDB 的相同问题。这也适用于 ElastiCache Redis。不需要任何默认 lambda 图像中没有的东西。
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));
}
回答by Cmag
Folks,
I've not been able to use the Promise.promisifyAll(Object.getPrototypeOf(dynamoDb));
伙计们,我一直无法使用 Promise.promisifyAll(Object.getPrototypeOf(dynamoDb));
However, the following worked for me:
但是,以下对我有用:
this.DYNAMO = Promise.promisifyAll(new AWS.DynamoDB());
...
return this.DYNAMO.listTablesAsync().then(function (tables) {
return tables;
});
or
或者
var AWS = require('aws-sdk');
var S3 = Promise.promisifyAll(new AWS.S3());
return S3.putObjectAsync(params);
回答by nackjicholson
CascadeEnergy/aws-promised
CascadeEnergy/aws 承诺
We have an always in progress npm module aws-promisedwhich does the bluebird promisify of each client of the aws-sdk. I'm not sure it's preferable to using the aws-sdk-promisemodule mentioned above, but here it is.
我们有一个始终在进行的 npm 模块aws-promised,它对 aws-sdk 的每个客户端执行 bluebird 承诺。我不确定使用aws-sdk-promise上面提到的模块是否更可取,但它是。
We need contributions, we've only taken the time to promisify the clients we actually use, but there are many more to do, so please do it!
我们需要贡献,我们只花时间向我们实际使用的客户端承诺,但还有很多事情要做,所以请做吧!
回答by joe
This solution works best for me:
这个解决方案最适合我:
// Create a promise object
var putObjectPromise = s3.putObject({Bucket: 'bucket', Key: 'key'}).promise();
// If successful, do this:
putObjectPromise.then(function(data) {
console.log('PutObject succeeded'); })
// If the promise failed, catch the error:
.catch(function(err) {
console.log(err); });

