javascript - Promise.map not waiting for resolution before proceeding to .then() -


i've had problem trying wrap mind around javascript promises. here lately frustration:

var rp = require('request-promise');  function process1000() {     //gets 1000 objects db process     get1000objects()     .then(function (docs) {         promise.map(docs, addapidata)         })     .then(function (objects) {             console.log(objects)         })     }  function addapidata(element) {     return rp(url).then(function (res) {         resolve(res);     })         .catch(console.error); } 

when rp(url) called in addapidata(), doesn't wait until function resolved before beginning next item in array i'm passing promise.map in process1000(). rp(url) called in addapidata, addapidata called on next item in array. second .then() function in process1000 called, prematurely before has had chance resolve in promise.map. i've tried few different libraries make request they're having same issue. doing wrong here? appreciated.

i think you're looking more this:

var rp = require('request-promise');  function process1000() {     //gets 1000 objects db process     get1000objects()     .then(function (docs) {         return promise.map(docs, addapidata)     })     .then(function (objects) {         console.log(objects);     }) }  function addapidata(element) {     return rp(url)     .catch(console.error); } 

the main point here need make sure you're returning promises, or next then won't know value.

also, try avoid promise constructor antipattern.

in other words, if return promise, don't need return then well.

these 2 equivalent:

return rp(url).then(function(res) { return res; });  // ,  return rp(url); 

they both return promise (rp(url) returns promise, , rp(url).then( /* ... */) returns promise).


Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -