我正在尝试使用一个调用外部API的Google Cloud函数。我在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'
因此,它就像是在无限循环中一遍又一遍地调用函数,并且每次都超时,直到它最终超时,客户端才会返回任何东西。我在这里做错了什么?
发布于 2019-05-23 03:01:39
由于您调用的是第三方异步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
逻辑。
https://stackoverflow.com/questions/56266941
复制相似问题