我正在讨论Firebase云功能的一个问题。我有一个onWrite云函数,它触发一系列事件。我有一个onWrite云函数绑定的请求路径。当该云函数执行时,它将删除对请求路径的新请求,并将请求推入一个呈现路径/que,该路径/que将用于客户端呈现UI元素/数据。一旦数据被写入呈现路径,我就调用不绑定到任何云事件的函数。vanilla javascript函数应该扩展到外部API,并获取一些数据,以便稍后更新被推入呈现路径的render对象。
问题是vanilla javascript函数永远不会执行。我一直在网上寻找原因,但似乎找不出原因。我在火焰计划,所以出站api请求应该允许我知道。这里是我的代码示例:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const request = require('request');
admin.initializeApp();
exports.requestModule = functions.database.ref('/requests').onWrite((change, context) => {
// Create reference to database
let db = admin.database();
if (context && context.auth && context.auth.uid) {
const afterData = change.after.val();
let uid = context.auth.uid;
let cleanData = afterData[uid];
cleanData.status = "loading";
// Remove the requested module from the requests path
let cleansePath = db.ref('/requests/' + uid);
cleansePath.remove().then((snapshot) => {
return true;
}).catch((error) => {
console.log(error);
return false;
});
// Add requested module to the render path
let renderPath = db.ref('/render/' + uid);
renderPath.push(cleanData).then((snapshot) => {
let val = snapshot.val();
let key = snapshot.key;
// Trigger the get weather api call
getWeather(uid, key, val);
return true;
}).catch((error) => {
console.log(error);
return false;
});
}
});
// Fetches data from external api
function getWeather (uid, key, obj) {
console.log('Fetching weather!');
let db = admin.database();
request('https://api.someweathersite.net/forecast/', (error, response, body) => {
if (!error && Number(response.statusCode) === 200) {
console.log('error:', error);
console.log('statusCode:', response && response.statusCode);
console.log('body:', body);
obj.data = body;
obj.status = 'loaded';
// Set data from api response in render object to be shown client side
let render = db.ref('/render/' + uid + '/' + key );
render.set(obj).then(() => {
return true;
}).catch((error) => {
console.log(error)
return false;
});
}
});
}
“console.log”函数顶部的getWeather消息永远不会执行。我不认为"getWeather“函数正在执行。
如果我将api调用直接放在onWrite "requestModule“函数中,则api调用将工作。但是,当它调用一个外部函数时,它永远不会被调用/工作。我基本上想让"requestModule“函数处理所有请求,并计划有一个模块调度程序来处理应该从哪个模块获取函数/api数据。这就是为什么我不想将api调用保留在"requestModule“函数中。知道为什么会发生这样的事吗?或者我怎样才能让这件事发生?
发布于 2018-08-11 17:50:23
getWeather正在执行异步工作以获取某些数据,但它没有返回指示该工作何时完成的承诺。实际上,您在这里执行的异步工作都没有正确地使用各种API调用返回的承诺。仅仅在每个承诺上使用then()是不够的。
您需要跟踪异步工作的 all ,并返回一个仅在所有工作完成后才能解决的承诺。否则,云函数可能会在工作完成之前终止和清理您的函数。(请注意,在强制终止之前,哪些工作可能或不实际完成并不是确定性的,但确保所有工作完成的唯一方法是通过您返回的单一承诺。)
您可能想看看我关于在云函数中使用承诺的教程,以便更好地处理需要做什么才能使您的函数正确工作:https://firebase.google.com/docs/functions/video-series/
https://stackoverflow.com/questions/51802248
复制相似问题