我正在使用 Cloud Functions for Firebase 通过 this 获取访问 token 之后我正在休息调用https://www.googleapis.com/auth/cloud-platform .但是在这样做的同时我得到了异常忽略来自已完成函数的异常。
我想知道为什么我会收到这条消息,背后的原因是什么。 #AskFirebase
已编辑 下面是我的 accessTokenHandler.js
const functions = require('firebase-functions');
var googleAuth = require('google-oauth-jwt');
const predictor=require("../prediction/predictor");
module.exports.getAccessToken=() =>{
googleAuth.authenticate({
email: 'my.gserviceaccount.com',
keyFile: "./accesstoken/key2.pem",
expiration: 3600000,
scopes: ['https://www.googleapis.com/auth/cloud-platform']
}, function (err, token) {
if(token){
console.log("token:"+token);
predictor.predict(token);
}
if(err)console.log("err:"+err);
});
}
下面是我的 predictor.js
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
module.exports.predict=(accessToken) =>{
predictImage(accessToken);
}
function predictImage(accessToken){
var httpRequest= new XMLHttpRequest();
httpRequest.open("POST","url",true);
httpRequest.setRequestHeader("Content-Type","application/json");
httpRequest.setRequestHeader("Accept","application/json");
httpRequest.setRequestHeader("Authorization", "Bearer " + accessToken);
httpRequest.send(getRequestJson());
httpRequest.onreadystatechange =function(){
if(this.readyState==4){
console.log("status:"+this.status+" state:"+this.readyState)
console.log("response:"+this.responseText)
}
}
}
function getRequestJson()
{
var b64Image='/9j/oAxt--encoded---f/2Q==';
var requestJson={"instances":
[{"key":"input_cloudfunction.jpg","image_bytes":{"b64":b64Image}}]};
return requestJson;
}
还有我的 index.js 文件
const functions = require('firebase-functions');
exports.handleFreshAccessToken = functions.https.onRequest((request, response) => {
response.send("Hello from Firebase!");
const accessHandler=require("./accesstoken/accesstoken_handler");
return accessHandler.getAccessToken();
});
最佳答案
您的代码在完成之前发生了一些错误。对于 HTTPS 类型的函数,它们在向客户端发送响应时正式结束。在您的代码中,您立即向客户端发送响应,这意味着您在此之后所做的所有其他事情都发生在“函数完成之后”。
如果您在一个函数中有异步工作要做,您应该在发送响应之前等待所有这些工作完成(使用 promise )。
关于node.js - 忽略 Cloud Functions 中已完成函数的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48288406/