0

I'm trying to identify the resolved promises in a loop using q module in NodeJS.

    var portscanner = require('portscanner');
    var Q = require('q');

    var portScan1 = function(ip) {
     return portscanner.checkPortStatus(22, ip);
    }

    var portScan2 = function(ip) {
     return portscanner.checkPortStatus(80, ip);
    }

    for(var i=1; i<=254; i++) {
     var ip = '10.10.1.' + i;
     Q.all([portScan1(ip), portScan2(ip)]).then(function(resolve) {
      console.dir({ ip: ip, func1result: resolve[0], func2result: resolve[1] });
     });
    }

The problem is that the variable i goes to 99 until the first Q is resolved.

{ ip: '10.10.1.254', func1result: 'open', func2result: 'closed' }
{ ip: '10.10.1.254', func1result: 'closed', func2result: 'closed' }
{ ip: '10.10.1.254', func1result: 'closed', func2result: 'open' }
{ ip: '10.10.1.254', func1result: 'closed', func2result: 'open' }
... (and so on)

How can I resolve this issue so that I can identify the id for the resolved promise?

Thx

ktln2003
  • 1
  • 2
  • The for loop executes synchronously, and what it does is begin the deferred execution of 100 pairs of promises. What I don't understand is what you want to have happen. – danh Mar 27 '17 at 19:37
  • What I wanted was a way to know for what variable 'i' is the console printing the resolved promise. As an example let's say func1 = i * i and func2 = i + i (promises). I want the console to return: i=2 => { id: 2, func1result: 4, func2result: 4}; i=3 => { id: 3, func1result: 9, func2result: 6}. What it returns now is the same id which is 99 with the function results for each 'i' in the for loop: { id: 99, func1result: 9, func2result: 6 } – ktln2003 Mar 27 '17 at 20:06
  • your code would log a result for i == 1, i == 2 ... and very value of i until i == 99 ... the value of `i` is the `id` in the object that is sent to the console – Jaromanda X Mar 27 '17 at 20:29
  • I modified the code and added also the result. The promises are resolved after the 'i' variable reaches the end of the loop. – ktln2003 Mar 27 '17 at 21:27
  • Resolved with Immediately Invoked Functions. Thx – ktln2003 Mar 28 '17 at 08:31

0 Answers0