Why, when executing this cycle, I get the result of only the last xhr query? How to fix it?

for(var i = 0;i<urls.length;i++) { xhr1 = new XMLHttpRequest(); xhr1.open("GET", urls[i], true); xhr1.send(null); xhr1.onreadystatechange = function() { if (xhr1.readyState == 4) { console.log(xhr1.status); if (xhr1.responseText) { var dat = xhr1.responseText; var str = dat.substring(dat.indexOf('filehd')+9,dat.indexOf('.mp4',dat.indexOf('filehd'))+4); $('#wrapper').append(str+'\n'); } } } } 
  • it is cross domain requests they must be asynchronous, synchronous chrome does not pass, does xhr1.onreadystatechange = function () ... wait until the request is executed? .. - Bond
  • Because your requests, being асинхронными , are executed in parallel, javascript does not wait for the end of the request. You can make синхронные requests. To do this, replace the second parameter in the function xhr1.open with true to false : xhr1.open("GET", urls[i], false); Но синхронные запросы считаются плохой практикой и в современных браузерах могут не работать в главном потоке. There are also options with asynchronous requests, but too complex for comment. - Sergey
  • onreadystatechange is the same callback. He is not waiting for anything by definition. It is called by the browser when it sees fit. - Sergey
  • You can write how to make each request waiting for the download to complete, otherwise it turns out that I only get the result of the latter and there may be 50+ - Bond

1 answer 1

Your problem is that you rewrite xhr1 with each iteration.
It turns out that nothing had time yet to load, but the loop wiped past XMLHttpRequest instances, the last one remained.


Better fetch :

 ['http://uri1.net', 'http://uri2.org'].forEach(uri => { fetch(uri) .then(r => r.text()) // Получаем ответ как текст .then(data => { // Работа с ответом тут через data }) }); 
  • works, thanks for the decision - Bond
  • @Bond, please, thank you here for expressing in the pros and, if the answer helped, by accepting the answer (tick to the left of the answer). - user207618
  • 1 more question: in the extension popup.html is generated using js how can I open this resulting page in a new tab (programmatically) without re-generating the page - Bond
  • @Bond, opening new tabs / windows is a delicate topic. Usually solved through windw.open('http://google.com/', '_blank'); but it is often cut. - user207618
  • I display the information $ ('# wrapper'). append (str + '\ n'); what is on popup.html (scripts are executed in the same place), how can I allow this wrapper to be thrown into a local html file that I will open after clicking on the extension icon - Bond