首页 > 解决方案 > 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(???)
  }

标签: javascriptamazon-web-servicesasynchronousasync-awaitamazon-dynamodb

解决方案


问题是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 没有任何关系,它纯粹是一个异步问题:查看这个深受喜爱的答案以获取更多信息:如何从异步调用返回响应?


推荐阅读