异步函数返回未定义 [英] Async function is returning undefined
问题描述
我真的需要重新审视我的异步等待和承诺.我希望得到一些建议.
我正在对Firebase Firestore进行异步函数调用.该函数应根据单个输入参数返回字符串.
此功能适用于1-1用户聊天.该功能是创建聊天/查找现有聊天,并返回其ID.
现在,我得到 undefined
作为 openChat
的返回值,无法弄清原因.除了返回以外,该函数还可以正常工作.
我有两个职能.一个是React类组件生命周期方法,另一个是我的firebase异步函数.
这是类组件生命周期方法:
async getChatId(userId){让chatPromise =新的Promise((解决,拒绝)=> {解析(openChat(userId))})让chatId =等待chatPromiseconsole.log('chatId',chatId)//未定义返回chatId}异步requestChat(userId){让getAChat = new Promise((resolve,reject)=> {解析(this.getChatId(userId))})让结果=等待getAChatconsole.log('result',result)//未定义}使成为() {返回(< button onClick = {()=> this.requestChat(userId)}>获取ID</button>)}
这是异步函数:
//我的两个console.log调用都在控制台中正确显示//表示返回值正确(?)导出异步函数openChat(otherPersonId){const用户= firebase.auth().currentUserconst userId = user.uid消防员.collection('用户').doc(userId).得到().then(doc => {让chatsArr = doc.data().chats让existArr =chatsArr&&chatsArr.filter(chat => {返回chat.otherPersonId === otherPersonId})if(existsArr&∃ Arr.length> = 1){const theId = existArr [0] .chatId//更新日期,然后返回ID归还消防站.collection('聊天').doc(theId).更新({日期:Date.now(),}).then(()=> {console.log('现有聊天返回',theId)//完成了,我们只需要聊天ID返回Id})} 别的 {//不聊天,创建一个//将新聊天添加到聊天集合归还消防站.collection('聊天').添加({userIds:{[userId]:是,[otherPersonId]:是},日期:Date.now(),}).then(docRef => {//将新聊天添加到我的用户文档中const chatInfoMine = {chatId:docRef.id,otherPersonId:otherPersonId,}//将聊天信息添加到我的用户文档中消防员.collection('用户').doc(userId).更新({聊天:firebase.firestore.FieldValue.arrayUnion(chatInfoMine),})//将新聊天添加到其他聊天用户文档const chatInfoOther = {chatId:docRef.id,otherPersonId:userId,}消防员.collection('用户').doc(otherPersonId).更新({聊天:firebase.firestore.FieldValue.arrayUnion(chatInfoOther),})console.log('最终返回新的聊天ID',docRef.id)返回docRef.id})}})}
如果您有任何有用的提示,我将不胜感激!
预期结果是返回的字符串.该字符串正确显示在async函数的console.log中.
实际结果是异步函数的返回值未定义.
您不会从 openChat
函数返回任何内容,因此该函数将解析为 undefined
.
您必须写:
导出异步函数openChat(otherPersonId){const用户= firebase.auth().currentUserconst userId = user.uidreturn firestore//在这里,您需要返回诺言链的返回诺言.collection('用户').doc(userId).得到()/* .... */}
而 getChatId
和 requestChat
中的 new Promise
并没有多大意义.等待 openChat(userId)
或 this.getChatId(userId)
async getChatId(userId){让chatId =等待openChat(userId)console.log('chatId',chatId)//未定义返回chatId}异步requestChat(userId){让结果=等待this.getChatId(userId)console.log('result',result)//未定义}
I really need to brush up on my async await and promises. I would love some advice.
I'm making an async function call to firebase firestore. The function should return a string depending on a single input param.
The feature is for a 1-1 user chat. The function is to create the chat/find existing chat, and return its ID.
Right now, I am getting undefined
as the return value of openChat
and can't work out why. The function otherwise works, apart from the return.
I have two functions. One is a React class component lifecycle method, the other my firebase async function.
Here is the class component lifecycle method:
async getChatId(userId) {
let chatPromise = new Promise((resolve, reject) => {
resolve(openChat(userId))
})
let chatId = await chatPromise
console.log('chatId', chatId) //UNDEFINED
return chatId
}
async requestChat(userId) {
let getAChat = new Promise((resolve, reject) => {
resolve(this.getChatId(userId))
})
let result = await getAChat
console.log('result', result) //UNDEFINED
}
render() {
return (<button onClick = {() => this.requestChat(userId)}>get id</button>)
}
and here is the async function:
// both my console.log calls show correctly in console
// indicating that the return value is correct (?)
export async function openChat(otherPersonId) {
const user = firebase.auth().currentUser
const userId = user.uid
firestore
.collection('users')
.doc(userId)
.get()
.then(doc => {
let chatsArr = doc.data().chats
let existsArr =
chatsArr &&
chatsArr.filter(chat => {
return chat.otherPersonId === otherPersonId
})
if (existsArr && existsArr.length >= 1) {
const theId = existsArr[0].chatId
//update the date, then return id
return firestore
.collection('chats')
.doc(theId)
.update({
date: Date.now(),
})
.then(() => {
console.log('existing chat returned', theId)
//we're done, we just need the chat id
return theId
})
} else {
//no chat, create one
//add new chat to chats collection
return firestore
.collection('chats')
.add({
userIds: {
[userId]: true,
[otherPersonId]: true
},
date: Date.now(),
})
.then(docRef => {
//add new chat to my user document
const chatInfoMine = {
chatId: docRef.id,
otherPersonId: otherPersonId,
}
//add chat info to my user doc
firestore
.collection('users')
.doc(userId)
.update({
chats: firebase.firestore.FieldValue.arrayUnion(chatInfoMine),
})
//add new chat to other chat user document
const chatInfoOther = {
chatId: docRef.id,
otherPersonId: userId,
}
firestore
.collection('users')
.doc(otherPersonId)
.update({
chats: firebase.firestore.FieldValue.arrayUnion(chatInfoOther),
})
console.log('final return new chat id', docRef.id)
return docRef.id
})
}
})
}
If you have any useful tips whatsoever, I would be forever grateful to hear them!
Expected results are a returned string. The string is correctly displayed the console.log of the async function).
Actual results are that the return value of the async function is undefined.
You do not return anything from your openChat
function, so that function resolves to undefined
.
You have to write:
export async function openChat(otherPersonId) {
const user = firebase.auth().currentUser
const userId = user.uid
return firestore // here you need to return the returned promise of the promise chain
.collection('users')
.doc(userId)
.get()
/* .... */
}
And those new Promise
in getChatId
and requestChat
do not make much sense. It is sufficient to await the result of openChat(userId)
or this.getChatId(userId)
async getChatId(userId) {
let chatId = await openChat(userId)
console.log('chatId', chatId) //UNDEFINED
return chatId
}
async requestChat(userId) {
let result = await this.getChatId(userId)
console.log('result', result) //UNDEFINED
}
这篇关于异步函数返回未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!