简体   繁体   中英

pass data from callback (aws dynamodb scan) to outside

I am retrieving the data from dynamodb with aws's dbclient.scan function. I need to use the output data to retrieve data from another table. I am trying to assign the output of first db scan into variable that is outside of dbclient.scan. The problem is that I get empty variable eventhough I assigned data from dbclient.scan callback function. What should I do? Anyway, I haven't used promise and asynchronous concept. The following is the code that I wrote.

var tmp = []
docClient.scan(params, (error, result) => {
     if(error) { .......} 
     else{ var tmp1 = result.Items[0].data
           tmp.push(tmp1)
     }
});
console.log(tmp)//empty list

What should I do? Many thanks, Sea

I found this is the easiest way to do this is like this:

let request = new AWS.DynamoDB({apiVersion: '2012-08-10'})
let params = {
    TableName: 'YOUR_TABLE_NAME',
    Key: {
        'YOUR_KEY': { S: 'STRING_VALUE_TO_MATCH' }
    }
}
let result = await request.getItem(params).promise().then((data) => {
    return data.Item 
})
// Now you can use result outside of the promise.
console.log(JSON.stringify(result))

Make sure this is inside an async function and it should work for you. This isn't for a "scan" but the concept should be the same.

until someone shows me a sane way of doing this, with real life code examples, this approach will usually work fine:

 function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } let results; await dynamodb.scan({ TableName : 'your_table_name', Limit : 10 }, function(err, data) { results = data; }.bind(this)); while (results === undefined) { await sleep(1000); } 

You're misunderstanding how Javascript and callbacks work. Javascript will process the whole file from the top down instantly. So when you're doing the console.log(tmp) the DynamoDB scan above has not finished yet.

Try changing your code to the following to view the data from DynamoDB:

    var tmp = []
    docClient.scan(params, (error, result) => {
      if(error) { .......} 
      else {
        var tmp1 = result.Items[0].data
        tmp.push(tmp1)

        // now get item using results from scan   
        var params = {
          TableName: "mytable",
          Key: {
            KeyName: tmp1.KeyName
          }
        }
        docClient.get(params, (error, results) => {
          console.log(results)
        })

      }
    });

I would highly recommend taking a look at async/await ( Google results for tutorials ). This will make your life so much easier when dealing with nested callbacks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM