Z
Z
zifmezin2021-10-16 15:35:05
Node.js
zifmezin, 2021-10-16 15:35:05

How to save records to db in a loop on node.js?

I receive an array of data. There is a task - to save the obtained values ​​​​to the mysql database. At the same time, the field in the database is unique, so you need to skip duplicates and save the next unique values. But I just can’t cope with asynchrony in cycles and promises. What am I doing wrong?

let data = ;

const queryStart = (item) => {
    const sql = `INSERT INTO domain (domain) VALUES ${item}`;
    return new Promise((res, rej) => {
      connection.query(sql, (error, result) => {
        if(error.code == "ER_DUP_ENTRY") return rej(new Error('Такая запись уже есть'));
        return res(result);
      });
    });
}

for(var item for data) {
  queryStart(item).then(
    result => {
      console.log(result)
      process.exit();
    },
    error => {
      console.log(error)
      process.exit();
    }
  );
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Slava Rozhnev, 2021-10-16
@rozhnev

First, in NodeJS, remove the duplicates from the array.
Second, at the database level, declare unique keys.
And may ASCID be with you

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question