Ad
How To Avoid Nesting Promises In IF Statement
I know we should not nesting promises in functions and all my functions are without any nesting at all however I can't figure out how to avoid nesting promises in if-else statement in one of my function.
const staffRef = db.collection("staff").doc(uid)
return staffRef.get()
.then((doc) => {
if (doc.exists) {
return staffRef.delete()
.then(() => {
console.log("Employee ", uid, " profile has been deleted in staff collection")
return null
})
} else {
console.log("Employee ", uid, " had no dependencies")
return null
}
})
I don't think this is nesting but I still get warnings while deploying. How should I restructure this code to avoid nesting warning? I know there some similar answers out there but none of them have if else statement
Ad
Answer
You can throw an error and catch it, as follows:
const staffRef = db.collection("staff").doc(uid)
return staffRef.get()
.then((doc) => {
if (doc.exists) {
return staffRef.delete();
} else {
console.log("Employee ", uid, " had no dependencies")
throw new Error("Employee " + uid + " had no dependencies");
}
})
.then(() => {
console.log("Employee ", uid, " profile has been deleted in staff collection");
return null;
})
.catch(error => {
console.log(error);
return null;
});
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad