alexiusacademia / electron-db

Electron module that acts as database management and uses flat file database (json file) to store tables.
MIT License
87 stars 24 forks source link

insertTableContent is not working in loop #10

Closed VikrantShirvankar closed 6 years ago

VikrantShirvankar commented 6 years ago

This is my code -

const arr = ['product_1', 'product_2', 'product_3', 'product_4', 'product_5'];
    arr.map((product, i) => {
      const obj = {};
      obj.image_name = product;
      obj.index = i;
      console.log('obj', obj);
      return db.insertTableContent('customers', obj, (succ, msg) => {
        console.log(`Success: ${succ}`);
        console.log(`Message: ${msg}`);
      });
    });

This is Output - error_code

only single record is inserted in customers.json

alexiusacademia commented 6 years ago

Hi. Thanks for opening the issue. I'm currently working on the problem. I think it has something to do with the asynchronous task used in the library jsonfile that I included in electron-db. It happens when the method is used in a loop.

I will immediately upload the fix once I finished it. Thanks.

alexiusacademia commented 6 years ago

Here is the solution I made to handle the async task for the for loop:

const arr = ['product_1', 'product_2', 'product_3', 'product_4', 'product_5'];

const m = arr.map((product, id) => {
  const obj = {}
  obj.image_name = product;
  obj.index = id;

  return obj;
});

function delay() {
  return new Promise(resolve => setTimeout(resolve, 10));
}

async function delayedAction(item) {
  await delay();
  db.insertTableContent('customers', item, (s, m) => {
    console.log('Success: ' + s);
    console.log('Message: ' + m);
  })
}

async function insertData(m) {
  for (const item of m) {
    await delayedAction(item);
  }
}

insertData(m);

I will be writing a different method for the async and incorporate it into the library. For now, you can use the above example code.

VikrantShirvankar commented 6 years ago

Thanks. It work for me.. please inform me once you update the library..

alexiusacademia commented 6 years ago

Okay, I will.

alexiusacademia commented 6 years ago

Hi VikrantShirvankar, I just want to inform you I already updated the library incorporating the async task for inserting multiple rows (array of objects).

VikrantShirvankar commented 6 years ago

thank u..