I am trying to understand Promises in Javascript. I have a situation where my code has some "nested" promises, and when installing ESLint I was made aware that async functions in Promise executors is considered an anti-pattern. I have code along the lines of:
const main = (indata) => {
heavyOperation(indata).then( (res) => {
console.log(res);
}).catch( err => {
console.err(err);
}).finally( () => {
cleanUp();
}
}
async const heavyOperation = (indata) => {
return new Promise( (resolve, reject) => {
preProcess(indata);
try {
const result = await calculate(indata);
} catch (err) {
console.err('Error in calculation.');
reject(err);
}
const processedResult = postProcess(result);
resolve(processedResult);
}
}
const preProcess = (indata) => {
//preprocessing
}
async const calculate = () => {
// do stuff
}
const postProcess = (result) => {
//postprocessing
}
main(indata);
How can I refactor this code? Should I get rid of heavyOperation
returning the promise entirely? How can I then achieve the .then
, .catch
, .error
functionality?
在这种情况下,尝试使用Promise chaining 。
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.