Javascript 使用DynamoDB扫描重复项

Javascript 使用DynamoDB扫描重复项,javascript,amazon-dynamodb,Javascript,Amazon Dynamodb,我想扫描项目,避免使用重复的代码 所以,我尝试异步地使用for 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

我想扫描项目,避免使用重复的代码

所以,我尝试异步地使用for

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 '';

我错过了什么或误解了什么?

等待只是等待一个承诺或可实现的对象,但您正在使用wait和一个void函数,您使用DYNAMO_DB.scan作为回调styte函数

我的建议是,使用DYNAMO_DB.scan和Promise风格


你认为代码是最好的吗?我不这么认为,尤其是const-arr是没用的。那么,你能推荐一个更好的代码吗?@zynkn代表let i=0;i<10;i++而不是arr的常量i。如果你想得到一个唯一的代码,让我们使用whilecode===这样的while循环,在while的主体中,你生成一个代码,检查它,如果它是重复的,将代码值重置为,或者不返回代码。起初,我尝试使用for,但很可能它不适用于async。我认为while是一个更好的解决方案,但看起来有点危险。无论如何,非常感谢你的回复
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());
})();