0

I'm working on a project that connects to an api in which it first collects some ids in a list, and then it sends another request to that api using that id list.

In there, I have a method where it makes those api calls in a loop that iterates through the ids and collects them within a promise list that is then converted to a normal array using Promise.all(). This worked as expected until I added the setTimeout. Now, the program resolves well before any of the promises have been pushed. I'm pretty inexperienced in Javascript, so I'm sorry if this a pretty newbie question, but how can I modify this code so that it retains the setTimeout on each call while still properly resolving the promise array?

function getSets(list){
return new Promise(function(resolve, reject)
{
    if(typeof list == "string")
    {
        var ids = [list]
    }
    else var ids = list

    //console.log(ids)
    promises = [];
    ids.forEach((id, i) =>
    {
        setTimeout(function()
        {
            promises.push(getRequest('GET', "https://ballchasing.com/api/replays/" + id, success))

        }, i * 5000)
    })
    //resolve(promises)
    Promise.all(promises)
    .then((result) => {
        //console.log('all resolved ', result)
        resolve(result)
    })

})

}

  • 1
    You'll have to promisify the `setTimeout` and push that promise to the array immediately. I'd do `promises.push(delay(i * 5000).then(() => getRequest(....` Or avoid `Promise.all` entirely and just `await` in a `for` loop – CertainPerformance May 03 '22 at 21:45

0 Answers0