0

I'm using the fetch function to populate an array. I'm using (some of the) data form the first fetch to start another fetch. My problem is that I have to use a timeout otherwise my array stays empty (probably due to asynchronous calls).

let output = [];
fetch('url1')
.then(response => response.json())
.then((response) => {
    let postsArray = response["bla"]["blabla"]["blablabla"]["endpoint"];
    if (postsArray.length > 0) {
        for (let i = 0; i < postsArray.length; i++) {
            let postID = postsArray[i]["bla"]["endpoint"];
            fetch('url/' + postID + '/blabla')
            .then(response => response.json())
            .then((response) => {
                let userInfo = response["bla"]["blabla"]["endpoint"];
                let myItem = {};
                myItem["bla"] = userInfo["bla"];
                myItem["blabla"] = userInfo["blabla"];
                output.push(myItem);
            });
        }
    }
});
//which I don't want to use
setTimeout(function(){
    alert(JSON.stringify(output));
}, 3000);

Is it possible to get rid of the setTimeout()? I don't want to use an await or something (due to cross-browser issues).

Any thoughts on this?

dexter
  • 163
  • 2
  • 11

0 Answers0