Search code examples
javascriptasync-awaitpromisees6-promise

How to turn multiples promises dependent on each other's response into await and make sure all requests fire


I have an array of objects that has 3 items inside it. I'm iterating over it and during each loop i need to make 3 API calls that all depend on each other's response. So in total there should be 9 API requests completed.

const arrayOfObjects = [
  {
    first: 'thing',
    second: 'thing',
    third: 'thing'
  },
  {
    fourth: 'thing',
    fifth: 'thing',
    sixth: 'thing'
  },
  {
    seventh: 'thing',
    eight: 'thing',
    ninth: 'thing'
  },
]
const makeModuleAndBatteryPromises = () => {
  arrayOfObjects.map((obj) => {   

    createModules(obj.first).then((response) => {
      createBattery(response, obj.second).then(res => {
      assignAssets(res, obj.third).then(res => 'assignment done!');
      });
    });
  });
}
makeModuleAndBatteryPromises();

So looking at above code, it seems like i truly only have control over the first 3 API Calls in the 1st loop of arrayOfObjects. As i have assignAssets(res).then(res => 'assignment done!'); which will allow me to do some operation like refresh page or redirect once the 3rd promise is resolved in the first loop.

However i need to do some operation on the 9th/final promise. Here is what i tried trying to make it async await.


     const makeModuleAndBatteryPromises = async () => {
    
      const promises = arrayOfObjects.map(async obj => {
        const firstResponse = await createModules(obj.first);
        const secondResponse = await createModules(firstResponse, obj.second); 
        await assignAssets(secondResponse);
      });
    
        await Promise.all(promises)
         .then(res => //do some action after all 9 promises resolved)
      }

        makeModuleAndBatteryPromises()

Not quite achieving what i was expecting it to, can some1 please tell me what i'm missing?


Solution

  • if I understand correctly, you want the resolved value of the final assignAssets?

    You've possibly confused yourself with a mix of async/await and .then

    const makeModuleAndBatteryPromises = async() => {
    
        const promises = arrayOfObjects.map(async obj => {
            const firstResponse = await createModules(obj.first);
            const secondResponse = await createModules(firstResponse, obj.second);
            return assignAssets(secondResponse);
        });
    
        const res = await Promise.all(promises);
        const finalValue = res.at(-1); // or res[res.length-1];
        // do things with finalValue
    }
    makeModuleAndBatteryPromises()