Search code examples
javascriptpromisees6-promise

How do I move from promise chaining to async/await multiple promises?


I've searched a lot, tried many things but I can't come to a clean conclusion. I'm chaining a lot of Promises:

getInstalledComponents().call().then(response => {
    return {
        'installed_components': {
            'data': response
        }
    };
}).then((passed_data) => {
    return getDemosCategories().call().then(response => {
        return {...passed_data, ...{'demos_categories': response}};
    });
}).then((passed_data) => {
    return getDemosData().call().then(response => {
        return {...passed_data, ...{'demos_data': response}};
    });
}).then((passed_data) => {
});

I can't handle errors with this. I'd like to re-write this in such a manner that if one of them fails, all of them should fail and return.

I tried to asy/await each promise function, reached nothing. The promises that return the data I need are getInstalledComponents, getDemosCategories, getDemosData and each of them is a Promise-based AJAX call. It's basically resolved when the AJAX call comes back.

This doesn't look clean, nor useful. How can I re-write this to fit my requirements?


Solution

  • Utilizing Promise.all we are able to parallelize requests:

    Promise.all([
      getInstalledComponents().call(),
      getDemosCategories().call(),
      getDemosData().call()
    ])
    .then(([installedComponents, demosCategories, demosData]) => ({
      "installed-categories": { data: installedComponents },
      "demos-categories": { data: demosCategories },
      "demos-data": {data: demosData}
    }))
    .catch(e => handleSomeErrorForAnyOfRequestsAbove(e))
    

    Using async/await there still Promise.all will be needed:

    const result = {};
    try {
      const [installedComponents, demosCategories, demosData] = await 
        Promise.all([
          getInstalledComponents().call(),
          getDemosCategories().call(),
          getDemosData().call()
        ]);
      result["installed-components"] = installedComponents;
      result["demos-categories"] = demosCategories;
      result["demos-data"] = demosData;
    
    } catch(e) {
      handleSomeErrorFromAnyOfRequestFailed();
    }