【问题标题】:Google Cloud Function async with multiple fetch requests谷歌云函数与多个获取请求异步
【发布时间】:2020-11-27 12:24:33
【问题描述】:

我是 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        
};

【问题讨论】:

  • 你不能给secondFunction()打个电话吗?

标签: javascript asynchronous promise async-await google-cloud-functions


【解决方案1】:

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));
//...

【讨论】:

    【解决方案2】:

    这里是你想做的代码(替换获取 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 响应,它使用this 方法。

    【讨论】:

      猜你喜欢
      • 2019-12-21
      • 2020-07-06
      • 1970-01-01
      • 2023-02-17
      • 1970-01-01
      • 1970-01-01
      • 2018-12-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多