E
E
Erik Mikoyan2020-06-18 08:55:02
JavaScript
Erik Mikoyan, 2020-06-18 08:55:02

Why does the sequelize database create fewer items than it should in a loop, but everything is fine without the loop?

I need to get all the cities that are in the VK database. Without a cycle, a document is created for the entire thousand items, only 3-4 documents are created in the cycle. Why is this happening? what to do?

spoiler
const City = sequelize.define("city", 
  {
    id: {
      type: Sequelize.INTEGER,
      autoIncrement: true,
      primaryKey: true,
      allowNull: false
    },
    title: {
      type: Sequelize.STRING,
      allowNull: false
    },
    area: {
      type: Sequelize.STRING,
      allowNull: false
    },
    region: {
      type: Sequelize.STRING,
      allowNull: false
    },
  }
  );

  let offset = 0;
  let count  = 1;
  
  do {
    let response = await axios.get(`https://api.vk.com/method/\
database.getCities?\
&country_id=1&need_all=1&count=1000&offset=${offset}&\
access_token=${vk.vk.ACCESS_TOKEN}&v=5.110`);
    let items = response.data.response.items

    items.map(async function(item) {
      City.create({
        id: item.id,
        title: item.title,
        area: item.area ? item.area: '',
        region: item.region ? item.region: '',
      }).then(res => {console.log(res.title)})
        .catch(error => {console.log(error)})
    })

    offset += response.data.response.items.length;
    count = response.data.response.count;
    console.log(`offset: ${offset}\ncount: ${count}`);
  } while (offset != count);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Vodakov, 2020-06-18
@WaterSmith

I think you have a problem with the loop exit condition:

offset += response.data.response.items.length;
    count = response.data.response.count;
    console.log(`offset: ${offset}\ncount: ${count}`);
  } while (offset != count);

the loop is executed until the number of records received from the API is equal to the offset.
But, it will be equal to you already at the first iteration, it turns out that your loop will work once.
What do you output to the console?
console.log(`offset: ${offset}\ncount: ${count}`);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question