javascript - AWS DynamoDB:从 Promise 内部返回值
问题描述
我对 dynamoDB 有一个有效的异步调用:
async getCostCenterTagFromTable() {
// Create the DynamoDB service object
var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'});
var params = {
TableName: 'csv-table',
Key: {
'BusinessUse': {S: 'eWFM'}
},
ProjectionExpression: 'CostCenter'
};
try {
// Asynchronously retrieve value from DynamoDB
const costCenter = await ddb.getItem(params).promise();
return costCenter;
}catch (error) {
console.error(error);
}
}
我可以很好地查看返回的 Promise 中的内容,但我只是不知道如何从 then() 块中删除值并将其返回给另一个函数。我的 getCostCenterTagValue 函数需要返回一个字符串。该字符串愉快地驻留在 promise 的 then() 块中。我需要把它拿出来归还,但它总是以未定义的形式返回。我知道这是此调用的异步性质的问题,并且我已经尝试了一切以从 then 块中获取该值但无济于事。任何帮助将不胜感激!
getCostCenterTagValue() {
var costCenter = this.getCostCenterTagFromTable();
costCenter.then(console.log);
//INFO { Item: { AutoTag_CostCenter: { S: '1099:802:000000' } } }
var costCenterString = costCenter.then(data => {
console.log("Cost Center Tag:" + data.Item.AutoTag_CostCenter.S);
//INFO Cost Center Tag:1099:802:000000
return data.Item.AutoTag_CostCenter.S;
}).catch(function(err) {
console.log(err);
});
console.log(costCenter.then())
return costCenterString(???); // or return costCenter.then(???)
}
解决方案
问题是async getCostCenterTagFromTable()
返回一个承诺。因此,您需要使用await
它的值,如下所示:
async getCostCenterTagValue() {
var costCenter = await this.getCostCenterTagFromTable();
var costCenterString = costCenter.Item.AutoTag_CostCenter.S;
return costCenterString;
}
function logCostCenterTagValue() {
getCostCenterTagValue().then(console.log);
}
这与 AWS 或 Dynamo 没有任何关系,它纯粹是一个异步问题:查看这个深受喜爱的答案以获取更多信息:如何从异步调用返回响应?
推荐阅读
- windows - 随机批量停止服务无济于事
- f# - 仅在构建失败时调用 ActivateBuildFailureTarget
- javascript - 无法在循环中打开包含按钮的 CSS 模式
- vb.net - 我无法将登录用户的信息检索到 form2
- python - 随机挑选具有给定概率的项目
- javafx - JavaFX 媒体卷绑定
- nhibernate - 你将如何导出 NServiceBus 的 NHibernate Saga 映射?
- django - 如何在 django 中正确分配 through 属性?
- botframework - 如何获取组织中的 MS Teams 用户列表?
- r - 如果变量具有重复值,则从数据框中删除组