1

I need help with debugging this code/or learn efficient way to do it- I tried using bluebird.each to capture all executions within my forEach, but didn't get it work. Same with setting up a new promise with pure javascript. I need help how to execute my forEach FIRST and move on.

let arr = []; 
let fields = ['environment', 'habitat', 'earth]
Promise.each(fields, field => {
  nano.db.use(field).view('options', 'options')
    .spread((body, header) => {
      arr.push(body.rows);
  })
}).then(() => console.log(arr))
  • Expected outcome:

    arr to console.log ====> [1,2,3,4,5]
    
  • Actual outcome:

    arr is an empty array ====> [ ]
    

I see it's a problem with asynchronicity, but I can't seem to figure out how to actually make this work. any input or resources will be greatly appreciated!

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Harris Lee
  • 93
  • 1
  • 2
  • 7

1 Answers1

0

I haven't actually ran your code so sorry if I'm incorrect, but from looking at it and the bluebird docs I assume the correction you need to make is return your nano.db call wrapped in a promise inside the Promise.each

let arr = []; 
let fields = ['environment', 'habitat', 'earth']
Promise.each(fields, field => {
  return new Promise ((resolve, reject) => {
    nano.db.use(field).view('options', 'options')
      .spread((body, header) => {
        arr.push(body.rows);
        resolve();
      })
  });
}).then(() => console.log(arr))

I believe your assumption is right that you're having a problem with asynchronicity when getting an empty array back instead of what you expect. I'm assuming the .then method is firing before the nano.db gets back with the data.

I wrapped your call of nano.db in a promise so that it will await nano.db finishing since Promise.each supports returning promises inside it.

Bluebird's promise docs state with Promise.each.

If the iterator function returns a promise or a thenable, then the result of the promise is awaited before continuing with next iteration.

So, if a promise is not returned in your Promise.each and anything that is asynchronous happens inside then just as with a then or a catch method on a promise under the same circumstances.

As I do not know bluebird there may be a way to change that promise to be more bluebird like. The promise I wrapped around the nano.db call is just a normal es6 promise which bluebird may or may not have a different api for creating promises.

John
  • 7,114
  • 2
  • 37
  • 57