As Shreyansh Pandey suggeseted chain function calls when you are using .then()
ex. lets say I have a list to be fetched, filter on variety of conditions, transform the results and then write the results to a file, you can maybe sturucture it into like this
// try {} catch {} and throw if something goes wrong in these functions
const fetchData = async function(){
// Get thanos for me
}
const filterData = function(data){
// do your thing here and return something
}
const transformData = function(data){
// do your thing here and return something
}
const writeToFile = async function(data){
// write the data to a file
}
fetchData()
.then(filterData)
.then(transformData)
.then(writeToFile)
.catch(err => console.log(err)); // ES6
// The same with async await
async function main(){
try{
// You can make some tweaks here though.
data = await fetchData();
filteredData = filterData(data);
transformedData = transformData(filteredData)
await writeToFile(transformedData);
} catch(err => {
console.log(err)
})
}
main()
This gives anyone looking into the code a clear picture of whats going on.
Its always better to stick to one convention. If you are using .then() try to make it same through out the codebase. If you are using async/await wrap it in try/catch follow the same. But in situations where you face long chaining I suggest its better to go with then as you can see its easier to understand and clean.
Along with that use prettier prettier.io or code formatters to maintain a same visual structure through out projects or any linters to keep your code clean.