I have an array of urls like this
var urls = ["www.google.com", "www.yahoo.com"];
And I want to loop the urls and execute the asynchronous task inside the loop, and not go to the next element until the async task is complete. I know you can do this with promises, but I have problems with this. Here is what i have
var xmlReader = require('cloud/xmlreader.js');
function readResponse_async(xlmString) {
var promise = new Parse.Promise();
xmlReader.read(xlmString, function (err, res) {
if(err) {
promise.reject(err);
} else {
promise.resolve(res);
}
});
return promise;
}
for (i = 0; i < urls.length; i++) {
Parse.Cloud.httpRequest({
url: unionUrls[i],
}).then(function(httpResponse) {
try {
return readResponse_async(httpResponse.text)
} catch (e) {console.log(e)}
}
But now he did not wait for readResponse_async to finish, how can I wait for it?
thanks
EDIT
After reading the answer, I do a save in my database, and I have another array like this
var location = ['USA', 'England'];
And I do it like
function saveLoc_async(data, location) {
var i3, i4, i5, m,
TestItem = Parse.Object.extend("TestItem"),
promise = Parse.Promise.as();
for (i3 = 0; i3 < data.count(); i3++) {
(function(testItem) {
testItem.set("item", data.at(i));
testItem.set("location", location);
promise = promise.then(function() {
return testItem.save();
});
})(new TestItem());
}
Because with your answer I have
function retry() {
if (urlsUnion.length > 0) {
var nextUrl = urlsUnion.pop();
var nextLoc = location.pop();
Parse.Cloud.httpRequest({
url: nextUrl,
}).then(function(httpResponse) {
xmlReader.read(httpResponse.text, function (err, res) {
if(err) {
} else {
saveLoc_async(res, nextLoc);
retry();
}
});
});
}
}
SO, where should it retry();go, because now with saving sometimes it puts the second place with one of the first url elements? why does this happen?