promise已完成,但结果未定义



我有一个承诺,承诺里面的console.log给了我一个字符串,但我不能使用承诺外面的结果,因为结果是undefined

const docId = firebase
.firestore()
.collection('users')
.doc(user.uid)
.collection('payments')
.get()
.then(querySnapshot => {
querySnapshot.forEach(doc => {
console.log(doc.id);
return doc.id;
});
});
console.log(docId);

所以console.log(doc.id)返回一个值,但我不能得到结果,并在const docId之外使用它。是否有一种方法可以抓取doc.id的结果并在const docId之外使用它?

您永远不会在最后的.then语句中返回值。在承诺外使用值的一种方法是使用在承诺外定义的变量,或者您可以使用await:

// If you're in an async function you can use await to get the result of the promise
const docId = await firebase
.firestore()
.collection('users')
.doc(user.uid)
.collection('payments')
.get()
.then(querySnapshot => {
querySnapshot.forEach(doc => {
console.log(doc.id);
return doc.id; // The return here does nothing
});
// You need to return something here
return querySnapshot[0].id;
});
console.log(docId);

最新更新