为什么我的云函数返回最后一个返回值而不是以前的一个?



我在客户端有一个按钮,它帮助我测试后端功能的简化版本。出于某种原因,客户端(Android Studio中的Logcat)正在返回test button isUsernameAvailable: Success. result.data = 2000。当我查看Firebase控制台时,我看到代码达到了_isUsernameAvailable REACHED THEN。但是,我不明白为什么客户收到的是2000而不是5。如果它到达前面提到的部分,它后面的行读取return 5。为什么我的客户没有收到5?

客户机代码:

testbutton.setOnClickListener() {
functions = Firebase.functions
var data = hashMapOf<String, Any>()
data["username"] = "ThisUsernameDoesntExist" 
functions.getHttpsCallable("isUsernameAvailable")
.call(data)
.addOnSuccessListener {result ->
Log.e(tag, "test button isUsernameAvailable: Success. result.data = " + result.data.toString())
}
.addOnFailureListener {exception ->
Log.e(tag, "test button failure exception: $exception")
}
}

Cloud功能代码:

//Check if username is available (callable from client)
exports.isUsernameAvailable = functions.https.onCall(async(data, context) => {
const username = data.username 
await admin.firestore().collection('users').where('username', '==', username).limit(1).get()
.then(result => {
console.log('_isUsernameAvailable REACHED THEN ')
return 5
})
.catch(error => {
console.log('_isUsernameAvailable REACHED CATCH ')
return 6
})

return 2000
});

这个答案部分解释了代码中发生的事情。为了适用于您的情况,return 5只是从Firestore回调函数返回,它不会导致您的主函数进程结束。

一个解决方案是创建一个变量,在遇到事件时赋值,而不是返回它:

exports.isUsernameAvailable = functions.https.onCall(async(data, context) => {
const username = data.username 
var returnCode = 0
await admin.firestore().collection('users').where('username', '==', username).limit(1).get()
.then(result => {
console.log('_isUsernameAvailable REACHED THEN ')
returnCode = 5
})
.catch(error => {
console.log('_isUsernameAvailable REACHED CATCH ')
returnCode = 6
})

if (returnCode != 2000){
return returnCode
}

return 2000
});

最新更新