0

i have array of db like

const dbArr = ["http://localhost:5984", "http://xyz_couchdb.com:5984"]

data to insert

let data ={
            _id: 324567,
            name: Harry,
            gerder: male
        }

here is the logic i am using nano module

        return new Promise((resolve, reject) => {

            let res = [];
            let rej = [];
            let counter = 0;

            for(let i = 0; i < dbArr.length ; i++){
                dbArr[i].insert(data, (err, body) => {
                    err ? rej.push(err) : res.push(body)
                    if(counter === obj.dbArray.length -1){
                        rej.length ? reject(rej) : resolve(res)
                    }
                    counter++;
                })
            }
        })

what can be the best possible way to achieve this using promise or async module or anything.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
xExplorer
  • 19
  • 2

1 Answers1

0

In the following example, we gotta use Array.map to create one promise for each element of dbArr, then we gotta wait all promises to end using Promise.all. The catch is here so we handle the errors.

function getAll(dbArr) {
  return Promise.all(dbArr.map(x => x.insert(data)));
}

getAll(dbArr)
  .then((rets) => {
    // Handle the returns
    // They are in an array
  })
  .catch((err) => {
    // Handle the error
  });

EDIT :

Ok after checking out the documentation of node-couchdb (the one I suppose you use) - I saw that the .insert() method do not return a Promise but only a callback.

So we gotta transform the method, so it will return a Promise using util.Promisify()

const {
   promisify,
} = require('util');

function getAll(dbArr) {
  return Promise.all(dbArr.map(x => promisify(x.insert)(data)));
}

getAll(dbArr)
  .then((rets) => {
    // Handle the returns
    // They are in an array
  })
  .catch((err) => {
    // Handle the error
  });
Orelsanpls
  • 22,456
  • 6
  • 42
  • 69
  • Thanks for your help, but i am not getting the actual callback data inside the success array of promise.all.. actual callback data on successful insertion is { ok: true, id: '324567', rev: '1-7e8fb36ba459c88099d63e9938f8bcc3' } but i am getting something like – xExplorer May 29 '18 at 06:58
  • { "uri": { "protocol": "http:", "slashes": true, "auth": null, "host": "localhost:5984", "port": "5984", "hostname": "localhost", "hash": null, "search": null, "query": null, "pathname": "/harry", "path": "/harry", "href": "http://localhost:5984/harry" } – xExplorer May 29 '18 at 06:59
  • , "method": "POST", "headers": { "content-type": "application/json", "accept": "application/json", "host": "localhost:5984", "content-length": 65 } } – xExplorer May 29 '18 at 06:59
  • @xExplorer I've edited my post, it seems that the librairie you use do not support natively `Promises` – Orelsanpls May 29 '18 at 07:23