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?

kyun
  • 9,710
  • 9
  • 31
  • 66

1 Answers1

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());
})();
hoangdv
  • 15,138
  • 4
  • 27
  • 48
  • 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? – kyun Oct 30 '19 at 06:56
  • @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`. – hoangdv Oct 30 '19 at 07:07
  • 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 – kyun Oct 30 '19 at 07:11