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
    });
  });
2
  • You are not resolving promise, read docs Commented May 8, 2016 at 17:23
  • Thanks, I did but don't see how to do. Can you show me an example? Commented May 8, 2016 at 17:48

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.