Reputation: 57
I do not get any result after I run the "set( )" function to the "res" variable when running this code, meaning that the "res" variable is undefined even though the docuement gets created in firebase. I have tried .then() .catch() too and that doesn't give me any kind of result either. The document gets created and everything works, and I if I want I can just return the Promise no matter the outcome of the firebase function, but that feels like it's bad practice since Im overlooking a possible error right?
Can I somehow get a result from "set( )" function? or in some other way make sure that the "set( )" function is successful?
exports.create = async function(listId, name, link) {
const newLinkRef = db.firestore.collection('links').doc();
const data = {
id: newLinkRef.id,
listId: listId,
name: name,
link: link
};
var res = await newLinkRef.set(data);
console.log(res)
if (res.id) {
return new Promise(resolve => {resolve({error: null, linkId: res.Id})})
} else {
return new Promise(resolve => {resolve({error: "Error creating lint"})})
}
}
(I use the "set( )" function over the "add( )" funciton since I want to save the random created Id inside the object stored to, and this was the simplest way I could find to do that)
Upvotes: 0
Views: 168
Reputation: 599001
set()
returns a promise, but your use of await
consume that promise and leaves res
as the result that the promise wraps, which is void
. So undefined
seems correct there.
I think you're looking for:
try {
var res = await newLinkRef.set(data);
return {error: null, linkId: newLinkRef.Id};
}
catch (e) {
return {error: "Error creating lint"}
}
Alternatively you can not use await
, and you end up with:
return newLinkRef.set(data).then(() => {
return {error: null, linkId: newLinkRef.Id};
}).catch (e) => {
return {error: "Error creating lint"}
})
Upvotes: 2