1

Really, I've tried all ways, but I fail to find the solution.

As no English, and I'm using the google translator, I will explain the same thing several times in a row.

1º Try the For loop will wait until everything is finished within

2º I try to know that city is doing OK on an external web request. And like many cities, I need to break the cycle once I check the first city ok.

3º I need to go a json and execute an action while running and wait till it finishes to follow. Then get out of the cycle at any time.


I've been testing with several codes, but present here for better understanding.

---------------------------------------------------------------------

var city = 
[
    {'city':'madrid'},
    {'city':'barcelona'},
    {'city':'valencia'},
    {'city':'malaga'}
];

var vBreak = 0;

for (i in city){

    request('example.there-city.com/' + city[i].city ,function (error, response, read) {
        if (read == 'OK') { vBreak = 1}
    });

if (vBreak == 1){ break;}
}

var city = 
[
    {'city':'madrid'},
    {'city':'barcelona'},
    {'city':'valencia'},
    {'city':'malaga'}
];

var vBreak = 0;

for (i in city){

    (function(i) {
        request('example.there-city.com/' + city[i].ciudad ,function (error, response, read) {
            if (read == 'OK') { vBreak = 1}
        });
    })(i);

if (vBreak == 1){ break;}
}

Thank you

user3537531
  • 75
  • 2
  • 8
  • 1
    That is exactly why JavaScript is asynchronous: you can't wait until everything is finished, you have to use callbacks. Take a look at the async module for loops: https://github.com/caolan/async – jgillich Oct 24 '14 at 17:40
  • I'd really suggest you read and understand [this answer](http://stackoverflow.com/a/14220323/816620). It's about ajax calls, but the asynchronous concept is the same. You MUST really learn how asynchronous code works to program with it correctly and get the results you want. You cannot treat it the same as synchronous code. – jfriend00 Oct 24 '14 at 17:59
  • @jgillich JavaScript isn't really async. Maybe you consider Node.js, but the ECMAScript spec doesn't state "JavaScript is async" – Ryan Oct 24 '14 at 19:59

2 Answers2

1

Use async.eachSeries (as jgillich said) to perform each request in order like this:

async.eachSeries(city, function (item, cb) {
  if (vbreak !== 1) {
    request('example.there-city.com/' + item.city ,function (error, response, read) {
        if (read == 'OK') { vBreak = 1}
        cb();
    });
  } else {
    cb() // Skip
  }
}, function () { // we're finished
})

You'll need to add error handling probably.

Evan Shortiss
  • 1,638
  • 1
  • 10
  • 15
0

Try to use a recursive function. Just increment the counter, after the response came ...

Sathish
  • 2,056
  • 3
  • 26
  • 40