javascript - 谷歌云函数与多个获取请求异步
问题描述
我对 GCF 和 Javascript async 都是新手,并且一直在努力解决这个问题。我最初执行 fetch 调用,然后将该响应作为参数传递给第二个函数,然后该函数也执行单独的 fetch 调用。
在第二个函数期间,我的空初始化 json 获取添加到其中的属性,当该函数完成时,我想通知exports.helloHttp
然后执行res.end
并终止。
我试过链接一个额外的空then()
,但它似乎没有工作。
我的代码:
var json = {}; // <- gets properties added to it during secondFunction()
exports.helloHttp = (req, res) => {
fetch("firstfetchurl.com",requestOptions)
.then(result => result.json())
.then(response => {
// next take the result and create a new product
return secondFunction(response);
})
.catch(error => console.log('error', error));
// res.end(JSON.stringify(json)); <- this is what I want my cloud function to output, but only after secondFunction completes
};
解决方案
这是可以执行您想要的操作的代码(替换获取 URL 并设置适当的选项)
const fetch = require('node-fetch');
exports.helloHttp = async (req, res) => {
return fetch("https://jsonplaceholder.typicode.com/users/1/albums") // First fetch
.then(firstFetchResponse => firstFetchResponse.json())
.then(firstFetchResponse => secondFunction(firstFetchResponse)) // Second fetch
.then(secondFunctionResponse => secondFunctionResponse.json())
.then(finalResponse => res.json(finalResponse)) // This line sends your response to the client
.catch(error => { console.error('Error', error); res.status(500).send('Server Error') }); // In case an error, log and send an error response
};
async function secondFunction(data) {
// Logic of your second function. Here just does another fetch using the data from the first request
let firstAlbumId = data[0].id
return fetch(`https://jsonplaceholder.typicode.com/albums/${firstAlbumId}/photos`);
}
同样的功能可以使用await
这样的
exports.helloHttp = async (req, res) => {
try {
let response = await fetch("https://jsonplaceholder.typicode.com/users/1/albums") // Note the await on this line
.then(result => result.json())
.then(firstFetchResponse => secondFunction(firstFetchResponse))
.then(secondFetchResponse => secondFetchResponse.json());
res.json(response); // Finally you are sending the response here.
} catch (error) {
console.error(error);
res.status(500).send('Server Error');
}
};
package.json
最后,您还需要确保node-fetch
{
"name": "sample-http",
"version": "0.0.1",
"dependencies": {
"node-fetch": "^2.6.0" // This line must be there
}
}
为了发送 JSON 响应,它使用此方法。
推荐阅读
- elixir - 使用 Elixir 插值映射键
- magento-1.9 - 对 db Magento 1 中的每个客户执行操作
- flutter - 不能在行内展开
- python - Flaskr - 我无法在单元测试中关闭/清除缓存
- javascript - 如何通过JS更改悬停时直接相邻兄弟元素的CSS?
- c# - 将日期时间输入作为文本(不带或带时区)解析为 UTC
- amazon-web-services - 是否可以使用 AWS SAM 配置具有不同 lambda 版本的不同 API Gateway 阶段
- typescript - TypeScript 3.5:如何使用索引器符号更新对象属性?
- javascript - 使用jQuery选择一个不存在的ID
- php - Rocket Chat rooms.upload PHP Curl 不工作