Firebase云函数:http函数返回null



我想这样做。

  1. 我正在引入允许用户搜索本地餐馆的功能。
  2. 我创建了一个HTTP云函数,这样当客户端交付关键字时,该函数将调用外部API来搜索关键字,获取响应,并交付结果。在做#2,我需要做两个单独的url请求和合并的结果。

当我检查时,该函数调用API,获取结果并合并它们没有任何问题。但是,由于某种原因,它只向客户端返回null。

下面是代码:有人可以看看,并建议我在哪里做错了?

exports.restaurantSearch = functions.https.onCall((data,context)=>{
const request = data.request;
const k = encodeURIComponent(request);
const url1 = "an_url_to_call_the_external_API"+k; 
const url2 = "another_url_to_call_the_external_API"+k;
const url_array = [ url1, url2 ];

const result_array = [];
const info_array = [];
url_array.forEach(url=>{
return fetch(url, {headers: {"Authorization": "API_KEY"}})
.then(response=>{
return response.json()
})
.then(res=>{
result_array.push(res.documents);
if (result_array.length===2) {
const new_result_array_2 = [...new Set((result_array))];
new_result_array_2.forEach(nra=>{
info_array.push([nra.place_name,nra.address_name])
})
//info_array is not null at this point, but the below code only return null when checked from the client
return info_array;
}
})
.catch(error=>{
console.log(error)
return 'error';
})
})
});

提前感谢!

你应该使用Promise.all(),而不是在forEach循环中分别运行每个promise (fetch request)。如果result_array.length不是2,我也看不到函数返回任何东西。我可以看到你只有2个请求,但是处理所有可能的情况是很好的,所以如果条件不满足,请尝试添加一个返回语句。试着这样重构你的代码(我使用了一个async函数):

exports.restaurantSearch = functions.https.onCall(async (data, context) => {
// Do note the async                            ^^^^^
const request = data.request;
const k = encodeURIComponent(request);
const url1 = "an_url_to_call_the_external_API" + k;
const url2 = "another_url_to_call_the_external_API" + k;
const url_array = [url1, url2];
const responses = await Promise.all(url_array.map((url) => fetch(url, { headers: { "Authorization": "API_KEY" } })))
const responses_array = await Promise.all(responses.map((response) => response.json()))
console.log(responses_array)
const result_array: any[] = responses_array.map((res) => res.documents)
// Although this if statement is redundant if you will be running exactly 2 promises
if (result_array.length === 2) {
const new_result_array_2 = [...new Set((result_array))];
const info_array = new_result_array_2.map(({place_name, address_name}) => ({place_name, address_name}))
return {data: info_array}
}
return {error: "Array length incorrect"}
});

如果你只运行两个承诺,其他选项将是:

// Directly adding promises in Promise.all() instead of using map
const [res1, res2] = await Promise.all([fetch("url1"), fetch("url2")])
const [data1, data2] = await Promise.all([res1.json(), res2.json()])

也检查Fetch多个链接在forEach循环

最新更新