当使用Batch对象时,Cloud函数将停止执行



我使用谷歌云函数在bigQuery上执行查询,并将结果存储在firestore中。

我的问题是,一旦我尝试使用firestore批处理对象,云函数就会停止执行。

使用二分法,我认为当我包含批处理对象代码时,函数会突然停止工作。

我曾试图将函数的内存增加到1GB,但没有成功。(目前使用128mb)

const {BigQuery}  = require('@google-cloud/bigquery');
const {Firestore} = require('@google-cloud/firestore');
const bigquery   = new BigQuery  ();
const firestore  = new Firestore ();
const fsCollectionName = 'ul_queteur_stats_per_year';

const queryStr = "the bigquery query";

function handleError(err){
//skipped
}
/**
* Triggered from a message on a Cloud Pub/Sub topic.
*
* @param {!Object} event Event payload.
* @param {!Object} context Metadata for the event.
*/
exports.ULQueteurStatsPerYear = (event, context) => {
const pubsubMessage = event.data;
const parsedObject  = JSON.parse(Buffer.from(pubsubMessage, 'base64').toString());
console.log("Recieved Message : "+JSON.stringify(parsedObject));
//{ ul_id:parsedObject.ul_id }
const queryObj = {
query: queryStr,
params: {
ul_id: parsedObject.ul_id
}
};
bigquery
.query(queryObj)
.then((data) => {
console.log("Query Successful, # rows : "+data.length+" data[0].length:"+data[0].length);
//rows : [{"amount":367.63,"weight":2399.3,"time_spent_in_minutes":420}]
const rows = data[0];
console.log("Query Successful");
const batch       = firestore.batch();
console.log("Batch Created ");
console.log("Getting Collection");
const collection  = firestore.collection(fsCollectionName);
console.log("Getting Collection '"+fsCollectionName+"' retrieved");
//#####################################
for(let i=0;i<rows.length;i++)
{
console.log("getting a new DocId");
const docRef = collection.doc();
console.log("Adding to docRef='"+docRef.id+"' : "+JSON.stringify(rows[i]));
batch.set(docRef, rows[i]);
console.log("Added to batch");
}

console.log("Commiting batch insert");
batch.commit().then(() => {
console.log('Successfully executed batch');
});
//#####################################
})
.catch(err => {
handleError(err);
});
};

预期:

Firestore 中插入的数据

实际结果:

如果我删除//#####################################

然后我把每一根木头都放在斯塔克德里弗。(第一个说有420行)

如果我让代码介于//#####################################(或者只是batch.commit()部分,或者只是for循环部分)

我只得到第一个日志,然后什么都没有。

查询成功,#行:1个数据[0]。长度:420

即使我将整个代码放在带有异常console.log的try/catch块中,我也不会在堆栈驱动程序中看到错误。

解决方案

解决方案是返回bigquerypromise。

所以上面的代码应该改为:

return bigquery
.query(queryObj)
.then(...);

感谢Doug的帮助!

您需要返回一个promise,该promise在所有异步工作完成时解析。现在,您没有返回任何内容,这意味着在查询完成之前,函数将立即终止并关闭。

您需要注意代码正在使用的所有承诺,包括查询和所有批处理提交。您不能忽略任何API返回的任何承诺,否则工作将在完成之前终止。

最新更新