Reputation: 13216
In the code below, there are certain cases in which I might find myself on the wrong page and then re-route, if a particular condition is met. In such cases, how would I call an $http.get call from within my code, and wait for the html source code to be retrieved before continuing my script?
function checkUrl(url, size, code) {
return $http.get(url).then(function(response) {
var html = response.data;
var listedPage = utility.countClass(html, 'product-tile');
if(listedPage > 1) {
url = getCorrectPage(html, code);
// this doesn't work, but I want to acquire the html of the newly acquired url
$http.get(url).then(function(response) {
html = response.data;
});
}
stockData.name = getProductName(html);
return stockData;
});
}
Upvotes: 0
Views: 46
Reputation: 1725
How about something like this:
function checkUrl(url, size, code) {
return $http.get(url).then(function(response) {
var html = response.data;
var listedPage = utility.countClass(html, 'product-tile');
if(listedPage > 1) {
url = getCorrectPage(html, code);
return $http.get(url).then(function(response) {
html = response.data;
stockData.name = getProductName(html);
return stockData;
});
}
else {
stockData.name = getProductName(html);
return stockData;
}
});
}
Upvotes: 1
Reputation: 6580
The problem is that you are creating a logic that is not possible given the asynchronous nature of $http.get(url)
.
Asynchronous is like you are telling js: listen do this, and when it's finished call this function I'm passing to you. So you give him this instruction and it delegates it to another thread and continues to run your program immediately. When that thread returns it will run the function you passed to it. But this is always after the rest of your code has already finished executing.
So it's not possible to do what you want in the way your code is structured.
You have to reformulate so the action you want is contained in the function you pass to $http.get(url)
.
Upvotes: 0
Reputation: 48647
You can't write synchronous I/O in JavaScript. The closest thing to what you want is a Promise.
Upvotes: 0