How to use for await in proper way eslint ( sequence query)

Viewed 902

I want to insert an data in DB , the problem is when I loop array I want to check if it has same username I want to push data into that object in DB else I want to create new, I try to use Promise all , reduce , It's run into parallel but It's work when I use for await loop but the eslint said no restricted synctax is thier anyway to fix it into eslint format

here is my example data

  const data = [
  {
    username: "11"
    code:["22"]
  },
  {
    username: "11"
    code:["23"]
  }
]

what I expect data in DB is

  const dataInDB = [
  {
    username: "11"
    code:["22","23"]
  },
]

Here is what it work with for loop but eslint show error

for await (const item of data) {
  const findUser = await User.findOne({ username: item.username });
  if (findUser == null) {
    // add new data 
  } else {
    // push data code into findUser
  }

Here is what I try to use Promise all but It seems like the data add in parallel it didn't go into if else condition [ eslint didn't show up error in this way ]

await Promise.all(data.map(async (item) => {
    const findUser = await User.findOne({ username: item.username });
    if (findUser == null) {
      //add into db
    } else {
    //push data
    }
}));

here is my eslint config

{

    "env": {
        "browser": true,
        "commonjs": true,
        "es2021": true
    },
    "extends": [
        "airbnb-base"
    ],
    "parserOptions": {
        "ecmaVersion": 12
    },
    "rules": {
        "no-param-reassign": ["error", { "props": false }],
        "no-underscore-dangle": "off"

    },
    "globals": {
        "__basedir": "writable"
      }
    
}
3 Answers

It looks like the restricted syntax rule comes from the airbnb config you are extending: https://github.com/airbnb/javascript#iterators-and-generators . If you really don't want to adjust the config or add an exception, I believe you should be able to to use a normal for loop:

for (let i = 0; i < data.length; i++) {
  const item = data[i];
  const findUser = await User.findOne({ username: item.username });
  // ...
}

If you are using mongoose/mongoDB, you can solve the whole thing simply this way:

data.forEach(e=>{
  User.findOneAndUpdate({username:e.username}, {$push:{code:e.code}})
  .then(data=>console.log(data))  
  .catch(err=>console.log(err)) 
  })

Practically, i would first just disable eslint for this line.

// eslint-disable-next-line
for await (const item of data) {

If this is used more, then it would be best practice to configure eslint to allow this. See https://eslint.org/docs/rules/no-restricted-syntax

Related