0

I've been struggling for hours to understand what I'm doing wrong in the following:

This is a function that takes as an argument an array exampleArr:

const mapOverItemsArray= async (exampleArr) => {
    let resultObj= {};

    await Promise.all(exampleArr.map(async item=> {
        await timeout(1000);
        let result;
        try{
            const response = await axios.get(`...api/${item}`);
            result= processResponse(response)
        }catch(e){
            console.log(e);
        };

        resultObj= {
            ...resultObj,
            [item]: result
        };
    })
    );
    return resultObj;
};

It is intended to await for a function timeout, that returns a promise , because the API has /second usage limits:

function timeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
};

But it does not seem to wait, which I can tell by the error messages - namely too many requests. Additionally, this is how I call the mapOverItemsArray:

//... enclosing async function
 await mapOverItemsArray(exampleArr);
 //...rest

Thanks a lot !

Peter Malik
  • 403
  • 4
  • 14
  • 1
    1) You should `return result` from the inner function, which means an array of results falls out of `await Promise.all(...)`, which you should *then* merge into one object if you want to. That would be easier to follow than manipulating an outer scope variable from inside a `map` callback. 2) All those promises will be executed at the same time, so they'll all wait 1 second, and then all make requests immediately. You'll want to chain all of them if you want for each request to wait for the previous one. – deceze Oct 19 '22 at 14:40
  • @deceze Thanks so much for the reply! I have addressed your first point, whereas the second one, do you mean something like `timeout(1000).then(async()=>{ const response = await axios.get('....'); ticker = extractTickerFromApiResponse(response) })`? – Peter Malik Oct 19 '22 at 14:47
  • 1
    No. See the second duplicate above for how to create a mutually dependent chain of promises, instead of a parallel executing array of promises. – deceze Oct 19 '22 at 15:08

0 Answers0