我正试图拥有一个调用外部API的Google Cloud Function。我处于Blaze计划中,因此我应该能够进行外部调用。我有一个Express应用,并且有以下测试路线:
app.get('/helloWorld', (request, response) => {
response.send('Hello there');
});
app.get('/test', (request, response) => {
request.get("https://postman-echo.com/get?foo1=bar1&foo2=bar2", (error, res, body) => {
console.log('error:', error);
console.log('statusCode:', res && res.statusCode);
console.log('body:', body);
if(error) {
response.status(400).send(error);
}
response.status(200).send(body);
});
});
/ helloWorld路由工作正常,但是/ test路由每次都超时。如果我查看Firebase日志中的功能,就会看到:
9:19:29.837 PM
api
Function execution started
9:20:29.839 PM
api
Function execution took 60002 ms, finished with status: 'timeout'
9:21:09.263 PM
api
Function execution started
9:21:09.277 PM
api
Function execution took 14 ms, finished with status code: 200
9:21:13.515 PM
api
Function execution started
9:22:13.516 PM
api
Function execution took 60002 ms, finished with status: 'timeout'
因此,就好像它不断在无限循环中反复调用该函数,并且每次都超时,并且直到最终超时为止,什么都没有返回给客户端。我在这里做什么错了?
答案 0 :(得分:1)
由于您正在调用第三方异步API,因此必须在代码完成时告诉Cloud Functions。为此,您可以通过从函数中返回一个Promise,然后确保在完成所有(异步)工作后Promise得以解决。
app.get('/test', (request, response) => {
return new Promise((resolve, reject) {
request.get("https://postman-echo.com/get?foo1=bar1&foo2=bar2", (error, res, body) => {
console.log('error:', error);
console.log('statusCode:', res && res.statusCode);
console.log('body:', body);
if(error) {
response.status(400).send(error);
reject(error);
}
response.status(200).send(body);
resolve();
});
});
});
您可能要考虑使用request-promise
之类的库,以防止需要自己的Promise
逻辑。