Javascript Google云函数与多个获取请求异步
我对GCF和Javascript异步都是新手,一直在努力解决这个问题。我首先执行一个fetch调用,然后将该响应作为参数传递给第二个函数,该函数随后还执行一个单独的fetch调用 在第二个函数中,我的空初始化json将添加属性,当该函数完成时,我想通知exports.helloHttp,然后执行Javascript Google云函数与多个获取请求异步,javascript,asynchronous,promise,async-await,google-cloud-functions,Javascript,Asynchronous,Promise,Async Await,Google Cloud Functions,我对GCF和Javascript异步都是新手,一直在努力解决这个问题。我首先执行一个fetch调用,然后将该响应作为参数传递给第二个函数,该函数随后还执行一个单独的fetch调用 在第二个函数中,我的空初始化json将添加属性,当该函数完成时,我想通知exports.helloHttp,然后执行res.end并终止 我尝试链接一个额外的空then(),但它似乎不起作用 我的代码: var json = {}; // <- gets properties added to it during
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
};
var json={};//{
fetch(“firstfetchurl.com”,requestOptions)
.then(result=>result.json())
。然后(响应=>{
//接下来,获取结果并创建一个新产品
返回第二个函数(响应);
})
.catch(error=>console.log('error',error));
//res.end(JSON.stringify(JSON));result.JSON()
不是异步操作,因此不需要使用then()
块
exports.helloHttp = (req, res) => {
fetch("firstfetchurl.com",requestOptions)
.then(result => {
return secondFunction(result.json());
})
.catch(error => console.log('error', error));
//...
请注意,根据您helloHttp
函数的确切目标,您可能需要返回整个承诺链,如下所示:
exports.helloHttp = (req, res) => {
return fetch("firstfetchurl.com",requestOptions) // Note the return
.then(result => {
return secondFunction(result.json());
})
.catch(error => console.log('error', error));
//...
下面是您想要的代码(替换获取URL并设置适当的选项)
相同的函数可以像这样使用wait
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
对节点fetch
{
"name": "sample-http",
"version": "0.0.1",
"dependencies": {
"node-fetch": "^2.6.0" // This line must be there
}
}
对于发送JSON响应,它使用方法。您不能进行secondFunction()
回调吗?
{
"name": "sample-http",
"version": "0.0.1",
"dependencies": {
"node-fetch": "^2.6.0" // This line must be there
}
}