0

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?

1 Answer 1

1

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());
})();
Sign up to request clarification or add additional context in comments.

3 Comments

Do you think the code is the best? I don't think so, especially const arr is useless. So, can you suggest a better code?
@zynkn for (let i = 0; i < 10; i++) instead of for (const i of arr). IF you want to get a unique code, let use a while loop like while(code === ''), in body of while, you gen a code, check it, if it is duplicated , reset code value to '', or not return the code.
at first, I tried to use for() but AFAIK it doesn't work with async. and I think while() is a better solution but it looks like a dangerous little bit. anyway thank you so much for reply

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.