Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Promises and forEach

I am trying to fill the array with avatarIcon node from parsed xmls but my final array in res.view is empty plus the execution doesn't seem to reach return res.view function. How do I do this correctly?

function parseXML(xml) {
 var parsed
 parseString(xml, { explicitArray: false }, function(err, result) {
     parsed = result
 })
 return parsed
}

function findUsers() {
 return new Promise(function(resolve, reject) {
    User.find().exec(function(err, sids) {
        resolve(sids)
    })
 })
}

avatars: function(req, res) {
    var arr = []
    findUsers().then(function(result) {
        result.forEach(function(el) {
            getProfileXML(el.sid).then(function(result) {
                 arr.push(parseXML(result).profile.avatarIcon)
            })

        })
        return res.view('users', {
            users: arr
        })

    })

}
like image 294
Fiat Pax Avatar asked Jun 03 '26 11:06

Fiat Pax


1 Answers

You can use Promise.all to wrap a collection of promises. Here untested code to demonstrate the use, where the result of the expression is a promise too:

return findUsers().then(function(result) {

  var promises = result.map(function(el) {
    return getProfileXML(el.sid);
  });
  return Promise.all(promises);

}).then(function(values) {
  var arr = values.map(function(v) {
    return parseXML(v).profile.avatarIcon;
  });
  return res.view('users', {
    users: arr
  })
})
like image 61
Meiko Rachimow Avatar answered Jun 04 '26 23:06

Meiko Rachimow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!