kyun
kyun

Reputation: 10264

scan duplicates item with DynamoDB

I'd like to scan items and avoid to use duplicates code.

so, I am trying to use for-of asynchronously for it.

async function checkDupl(){
  const arr = new Array(10).fill(0);
  let code = '';
  for(const i of arr){
    //generate RANDOM CODE
    //for example, it would be '000001' to '000010'
    code = (Math.floor(Math.random() * 10) + 1).toString().padStart(6,"0");
    const params = { ... }; // it has filterExpression the code I generated randomly
    await DYNAMO_DB.scan(params, (err, res) => {
      if(res.Items.length === 0) {
        /* no duplicate! */
        return code;
      }
    }); 
  }
  return code;
}

console.log(checkDupl());
// it always return '';

What I have missed or misunderstood?

Upvotes: 0

Views: 355

Answers (1)

hoangdv
hoangdv

Reputation: 16127

await just waits a Promise (or thenable object), but you are using await with a "void" function (You use DYNAMO_DB.scan as a callback styte function).

My suggestion, Use DYNAMO_DB.scan with Promise style (The way)

async function checkDupl() {
  const arr = new Array(10).fill(0);
  let code = '';
  for (const i of arr) {
    //generate RANDOM CODE
    //for example, it would be '000001' to '000010'
    code = (Math.floor(Math.random() * 10) + 1).toString().padStart(6, "0");
    const params = { ... }; // it has filterExpression the code I generated randomly

    const res = await DYNAMO_DB.scan(params).promise(); // convert to promise

    if (res.Items.length === 0) {
      /* no duplicate! */
      return code;
    }
    return code;
  }
}

(async () => {
  console.log(await checkDupl());
})();

Upvotes: 1

Related Questions