Wednesday 24 May 2017

NodeJS, request-promises are not waiting for each other

So I have broken my issue down a simple code snippet.

I want the otherRequestes to wait for my firstRequests, but somehow this is not working. the firstRequested is never waited for

const rp = require('request-promise');

const firstRequest = () => {
  return rp('http://www.google.com')
    .then(function(htmlString) {
      console.log('in then of firstrequest');
    })
    .catch(function(err) {
      console.log('catch', err);
    });
}

laterRequest = (i) => {
  return rp('http://www.google.com')
    .then(function(htmlString) {
      console.log('in then' + i);
    })
    .catch(function(err) {
      console.log('catch', err);
    });

}

const requests = [];

for (let i = 0; i < 10; i += 1) {
  requests.push(laterRequest(i));
}

firstRequest().then(() => {
  Promise.all(requests).then(() => {
    console.log('all promises returned');
  });
});

So my desired output is "in then of firstrequest" after those there the output should be the laterRequests, I don't care for their order.

But when I run it currently my output is as follows the firstRequest ends up randomly somewhere in the output:

in then0
in then5
in then2
in then3
in then1
in then8
in then4
in then6
in then9
in then7
in then of firstrequest
all promises returned



via acid

No comments:

Post a Comment