node.js - Using Promise with CouchDB nano & forEach -


i need debugging code/or learn efficient way it- tried using bluebird.each capture executions within foreach, didn't work. same setting new promise pure javascript. need how execute foreach first , 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 console.log ====> [1,2,3,4,5]

-actual outcome: arr empty array ====> [ ]

i see it's problem asynchronicity, can't seem figure out how make work. input or resources appreciated!

thank you

i haven't ran code sorry if i'm incorrect, looking @ , bluebird docs assume correction need make return nano.db call wrapped in promise inside 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 assumption right you're having problem asynchronicity when getting empty array instead of expect. i'm assuming .then method firing before nano.db gets data.

i wrapped call of nano.db in promise await nano.db finishing since promise.each supports returning promises inside it.

bluebird's promise docs state promise.each.

if iterator function returns promise or thenable, result of promise awaited before continuing next iteration.

so, if promise not returned in promise.each , asynchronous happens inside then or catch method on promise under same circumstances.

as not know bluebird there may way change promise more bluebird like. promise wrapped around nano.db call normal es6 promise bluebird may or may not have different api creating promises.


Comments

Popular posts from this blog

c# - Update a combobox from a presenter (MVP) -

How to understand 2 main() functions after using uftrace to profile the C++ program? -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -