谷歌云功能异步与多个提取请求



我是GCF和Javascript异步的新手,一直在努力解决这个问题。我最初执行一个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响应,它使用了这种方法。

result.json()不是异步操作,因此不需要使用then()块。以下内容应该能起到作用;

exports.helloHttp = (req, res) => {
fetch("firstfetchurl.com",requestOptions)
.then(result => {
return secondFunction(result.json());
})
.catch(error => console.log('error', error));
//...

注意,根据helloHttp函数的确切目标,您可能需要返回整个promise链,如下所示:

exports.helloHttp = (req, res) => {
return fetch("firstfetchurl.com",requestOptions)  // Note the return
.then(result => {
return secondFunction(result.json());
})
.catch(error => console.log('error', error));
//...

相关内容

  • 没有找到相关文章

最新更新