简体   繁体   中英

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?

If you were to simply put a catch block at the end of the last then it would catch errors in any of the functions.

 Promise.reject("firstFailed") .then(passedData => console.log("second") || passedData) .then(passedData => console.log("third") || passedData) .then(passedData => console.log("fourth") || passedData) .catch(error => console.error(error)); 

As you can see from the lack of console logs in the example above, first rejection stops the execution of any other then block

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM