I have a few async methods that I need to wait for completion before I return from the request. I'm using Promises, but I keep getting the error:
Each then() should return a value or throw // promise/always-return
Why is this happpening? This is my code:
router.get('/account', function(req, res) { var id = req.user.uid var myProfile = {} var profilePromise = new Promise(function(resolve, reject) { var userRef = firebase.db.collection('users').doc(id) userRef.get() .then(doc => { // Error occurs on this line if (doc.exists) { var profile = doc.data() profile.id = doc.id myProfile = profile resolve() } else { reject(Error("Profile doesn't exist")) } }) .catch(error => { reject(error) }) }) // More promises further on, which I wait for })
The then() method returns a Promise . It takes up to two arguments: callback functions for the fulfilled and rejected cases of the Promise .
The . promise() method returns a dynamically generated Promise that is resolved once all actions of a certain type bound to the collection, queued or not, have ended. By default, type is "fx" , which means the returned Promise is resolved when all animations of the selected elements have completed.
The Promise. resolve() method "resolves" a given value to a Promise . If the value is a promise, that promise is returned; if the value is a thenable, Promise. resolve() will call the then() method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value.
resolve() method in JS returns a Promise object that is resolved with a given value. Any of the three things can happened: If the value is a promise then promise is returned.
Add at the end of the then()
return null
That's it.
Each then() should return a value or throw Firebase cloud functions
Just avoid the Promise
constructor antipattern! If you don't call resolve
but return a value, you will have something to return
. The then
method should be used for chaining, not just subscribing:
outer.get('/account', function(req, res) { var id = req.user.uid var userRef = firebase.db.collection('users').doc(id) var profilePromise = userRef.get().then(doc => { if (doc.exists) { var profile = doc.data() profile.id = doc.id return profile // I assume you don't want to return undefined // ^^^^^^ } else { throw new Error("Profile doesn't exist") // ^^^^^ } }) // More promises further on, which I wait for: // profilePromise.then(myProfile => { … }); })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With