1

I'm just starting with NodeJS. I try to do with NodeJS a loop and only then : send my result to an express template.

I tried many lib and promises but none of them worked. Node do "then" before ending the loop...

Here's my last try, can you help me with? Thanks a lot.

[...]
//pveIds contains list of dailies id (object)
var pveIds = body.pve;
//init tab, will contain dailies title
var pveNames = [];

Promise.map(pveIds, function(pveId) {
    // Promise.map awaits for returned promises as well.
    request.get({
        url: 'https://api.guildwars2.com/v2/achievements?id=' + pveId.id,
        json: true
      },
      function(error, response, body) {
        console.log('log 1: ' + body.name);
        if (response.statusCode == 200) {
          return body.name;
        }
      }).on('data', function(v) {
      console.log('log 2: ' + v);
      return v;
    });
  }).then(function(results) {
    console.log("done");
    console.log(results);
    console.log("names tab:" + pveNames);
    res.render('pve.ejs', {
      names: pveNames
    });
  });
Gwendoline
  • 11
  • 4

1 Answers1

1

You need to return request.get({... instead of just request.get({

The way you have it now your function(pveId) returns undefined so your Promise.map just registers a bunch of undefined's instead of actual promises.

You should also not mix promises with callbacks, use request-promise instead of request.

marton
  • 1,300
  • 8
  • 16