如何在Lambda Node.js中进行嵌套的dynamodb调用?

时间:2018-10-18 02:51:11

标签: node.js aws-lambda amazon-dynamodb aws-sdk

调用async / await函数并为另一个函数返回该数据时遇到了问题。

您将如何编写一个lambda nodejs文件,该文件:

A。调用externalFile.js并等待带有值的返回响应。 (调用dynamodb并询问它有多少项,返回10)

B。返回10后,主函数将10传递到另一个dynamodb调用中,以查询数字10。

C。调用ExternalFile2.js异步/唤醒响应,然后对该响应执行某些操作。

基本上,我的想法是,我想返回表的长度,然后查询表,然后更新表,所有这些操作均按照异步顺序进行,以便可以从第一个调用中获得数据。

您将如何处理?

我的函数返回null,并且从不执​​行任何console.logs dynamodb调用

const AWS = require('aws-sdk');
var DOC = require("dynamodb-doc");
let totalMade = null;
let dbTotal = null;
let contractInfo = {};
var getTotalMade = require('./web3.js')

const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'});

async function get() {
    try {
        totalMade = await getTotalMade.data.methods.getTotal();
       console.log(totalMade)
        return totalMade.total
    }
    catch(error) {
        return error;
    }
}



exports.handler = async function(event, context) {

AWS.config.update({ region: "us-east-2" });
//Check External Contract for totalMade result
let tokenAddress = "0x32659521996926TEST"
let totalSupply = get().then(res => console.log("index results : "+ res))
console.log(" This is my results: this is the get(): " + totalSupply);

//Gets results from totalSupply and console logs properly, but cannot call dynamodb. Nothing executes

  //call DB with totalMade as an arguement 
   var params = {
       TableName: "XYZ123"
   }
    dynamodb.describeTable(params, function(err, data) {
        if (err) {
            console.log(err, err.stack);
          return err
        } else {

               if(ID > data.Table.ItemCount){
                console.log(ID, data.Table.ItemCount)

                  dbTotal = data.Table.ItemCount;
                  console.log("end of fetch: " + dbTotal + " and the SC total: " + ID)

                  var docClient = new DOC.DynamoDB();
                  contractInfo.allCards.forEach(item1 => {
                      console.log("running loop: " + item1)
                     docClient.putItem({
                    TableName: 'XYZ123',
                    ConditionExpression: 'attribute_not_exists(item1)',
                               Item: {
    'cardID' : item1,
    'numberID' : dbTotal++ ,
  }

                  }).promise()
                  .then((err, res) => {
                      if(err)console.log(err)
                      if(res) {

                        callback(null, {
                statusCode: '200',
                body: {
                res
                }
            });      }            
                  })
                  })


               }
               if(ID <= data.Table.ItemCount){
                 callback(null, {
                statusCode: '500',
                body: {
                  uptoDate: true
                }
            });                  
           }


     }






}).catch(err  => {
  console.log(err)
})

};

index.js正在调用的我的外部文件:

     var tokenGen = require('./ERC721Generator.json');
    var ERC721a = require('./ERC721Token.json');
    var Web3 = require('web3');
    var web3 = new Web3(new Web3.providers.HttpProvider("https://rinkeby.infura.io/v3/API_KEY"));
    var version = web3.version.api; 
    const contract = require('truffle-contract');
    const tokenGenerator = contract(tokenGen);
    const ERC721 = contract(ERC721a);

    async function getItem(item){
       // Return new promise 
        return new Promise(function(resolve, reject) {
          // Do async job
           token.tokensArray().call(item, function(err, resp) {
                if (err) {
                    reject(err);
                } else {
                    resolve(JSON.parse(resp));
                }
            })
        })

    }
    var methods = {
      getTotal: async function() {

       tokenGenerator.setProvider(web3.currentProvider);
       ERC721.setProvider(web3.currentProvider);
     let contractInfo = {};  

    let token = await tokenGenerator.at("0xdf3d2033651212771a4f25d27d307e9f76de50b9")



//Can get this far, but nothing else runs after this
//Never gets into the while loop, why??



    let i = 0;
    contractInfo.total = await token.totalGenerated.call()
    while( i < contractInfo.total){
      getItem(i).then((err, res) => {
          contractInfo.allCards.push(res);
          console.log("inside loop" + contractInfo.allCards)
          i++
        })
      }

    return contractInfo
    }




    }


    exports.data = {
      methods
    }

1 个答案:

答案 0 :(得分:0)

如何?

export default async (event, context, callback) => {
   [err,data ] = await promiseToObject(dynamoClient.put(//params).promise())

   if(err) {
     //handle err
     callback(err, null)

   }

  // results.Items has the returned data


  // do another await!

}

function promiseToObject(promise) {
    return promise.then((data) => {
        return [null, data]
    }).catch(err => [err])
}

如果不清楚,我将进行更新,但是基本上您可以使用await依次处理数据,不需要回调,等等!

请注意PromiseToObject不是我的代码,我将尽快提供引用!

如果要将dynamo调用抽象到另一个脚本中,只需要从dynamoDB调用中返回promise,就可以等待它。