我正在尝试从android执行Callable函数。
这是功能代码 -
const Translate = require('@google-cloud/translate');
const projectId = functions.config().firebase;
const translate = new Translate({
projectId: projectId,
});
exports.translateMessage = functions.https.onCall((data, context) => {
let text = data.text;
let targetLanguage = data.target_language;
let uid = context.auth.uid;
console.log("incoming text: " + text)
console.log("incoming uid: " + uid)
console.log("incoming target: " + targetLanguage)
//In future, check if uid or custom claim has quota
if(!uid)
return text;
translate
.translate(text, targetLanguage)
.then(results => {
const translation = results[0];
console.log("translated text: " + translation)
return Promise.resolve(translation);
//also tried returning json like: return {translationText: translation};
})
.catch(err => {
console.log(err)
return Promise.reject(err);
});
});
正如您所看到的那样,在使用已翻译文本返回承诺之前,它已成功记录到控制台。我还通过返回翻译文本本身而不是承诺进行测试。在客户端仍然无效。
这是客户端代码 -
private Task<String> translateMessage(String text, String targetLanguage) {
// Create the arguments to the callable function.
Map<String, Object> data = new HashMap<>();
data.put("text", text);
data.put("target_language", targetLanguage);
FirebaseFunctions mFunctions = FirebaseFunctions.getInstance();
return mFunctions
.getHttpsCallable("translateMessage")
.call(data)
.continueWith(new Continuation<HttpsCallableResult, String>() {
@Override
public String then(@NonNull Task<HttpsCallableResult> task) throws Exception {
String result = (String) task.getResult().getData();
Log.d(TAG, "Result in callable callback: " + result);
return result;
}
});
}
可调用回调的结果始终为null。
知道如何获得实际响应吗?
答案 0 :(得分:4)
我已经找到了解决方案,我的Javascript天真就应该受到责备。
看起来只有我使用两个return语句,然后将实际的字符串发送回客户端。实际承诺前面的return关键字丢失了......
return translate
.translate(text, targetLanguage)
.then(results => {
const translation = results[0];
console.log("translated text: " + translation)
return Promise.resolve(translation);
})
.catch(err => {
console.log(err)
return Promise.reject(err);
});