首页 > 解决方案 > 谷歌云函数与多个获取请求异步

问题描述

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

标签: javascriptasynchronouspromiseasync-awaitgoogle-cloud-functions

解决方案


这是可以执行您想要的操作的代码(替换获取 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 响应,它使用方法。


推荐阅读