Within a Chrome Extension i make multiple get requests and want to find out for which of the get requests the result has a match with a given string.
Because of the asynchronous call my "logging" which url i am analysing is not up to date, when i make the string match.
What i tried:
Going for r.url. But i am not sure this can be done to handover the value together with r.text(). Also i tried to make nested .then() calls, but that didnt work out.
Reproducible / example Code:
urls = ["https://stackoverflow.com/questions/tagged/javascript", "https://stackoverflow.com/questions/tagged/python"];
for (var reqNr = 0; reqNr < urls.length; reqNr++) {
reqUrl = urls[reqNr];
var AjaxPromise = fetch(reqUrl);
console.log("reqUrl");
console.log(reqUrl);
AjaxPromise.then(r => r.text()).then(result => {
if(result.includes("javascript")){
console.log(result);
// This is the wrong Url now, because of the asynchronity
getUrl = reqUrl;
console.log("reqUrl2");
console.log(reqUrl); // will only show the last url in loop because of the asynchronity.
// I could take r.url, but i am not sure i can also pass it together with result: https://stackoverflow.com/questions/28703625/how-do-you-properly-return-multiple-values-from-a-promise.
console.log("Found match for url: ", reqUrl); // not the "correct" reqUrl
// console.log("Found match for url: ", r.url); DOESNT WORK
}
});
}
It might be solved dispensing the asychronity, but I would prefer to stay with the asynchronity due to Performance issues..