【发布时间】:2021-08-27 12:13:44
【问题描述】:
我有一个调用复杂任务的云函数(具有许多不同的异步任务)。在这些任务结束时,将发送一个事件“完成”并由云函数捕获,该函数将终止,例如:
exports.myFunction = functions.https.onRequest(async (request: any, response: any) => {
cors(request, response, async () => {
doSomethingComplex(); // no returned value possible here, but many asynchronous tasks done
eventEmitter.on('finished', (data) => { // finished is properly sent at the end of the asynchronous tasks
functions.logger.debug('done : ', data); // is always clean with only 1 occurence at each function call
response.send({something: data.something}); // <--- THIS IS WHERE THE ERROR OCCURE
}
});
});
目前,每个异步任务在每次调用时都能完美完成。但恰好有两次,response.send() 出错并出现以下错误堆栈:
at ServerResponse.send (/layers/google.nodejs.functions-framework/functions-framework/node_modules/express/lib/response.js:170:12)
at ServerResponse.json (/layers/google.nodejs.functions-framework/functions-framework/node_modules/express/lib/response.js:267:15)
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:530:11)
at ServerResponse.send (/layers/google.nodejs.functions-framework/functions-framework/node_modules/express/lib/response.js:158:21)
at ServerResponse.header (/layers/google.nodejs.functions-framework/functions-framework/node_modules/express/lib/response.js:771:10)
at EventEmitter.<anonymous> (/workspace/lib/src/index.js:235:37)
Function execution took 3354 ms, finished with status: 'crash'
我尝试使用response.end(),我尝试返回response.send(),但一切都失败了。
我还记录了每个异步任务,以确保它们在发送“完成”事件之前全部完成,并且该部分的一切都是干净的。
我不明白 response.send() 如何可以在任何时候调用云函数时只调用一次,但仍会触发Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client 每两次调用一次(1 次成功,1 次错误,1 次成功,1 次错误) .
这对我来说没有意义,就像在 response.send() 之后没有关闭云功能一样(根据this answer 这是不可能的)
有人有想法吗?将不胜感激!
【问题讨论】:
标签: javascript node.js typescript firebase google-cloud-functions