简体   繁体   English

ExpressJS 使用助手 function 创建多个 JSON 对象

[英]ExpressJS creating multiple JSON objects with helper function

I'm trying to create multiple JSON objects using an external call out to FourSquare API with different query parameters, but my code keeps returning as a successful response code with no readable results.我正在尝试使用具有不同查询参数的 FourSquare API 的外部调用来创建多个 JSON 对象,但我的代码一直作为成功的响应代码返回,没有可读的结果。 Here is the code I'm trying to use:这是我尝试使用的代码:

async function getPlaces(query, lat, lon, clientID, clientSecret, versionDate) {
    const URL = `https://api.foursquare.com/v2/venues/search?client_id=${clientID}&v=${versionDate}&ll=${lat},${lon}&intent=browse&radius=10000&query=${query}&limit=10&client_secret=${clientSecret}`;
    const response = await fetch(URL).catch(e => { console.log(e) });
    const data = await response.json().catch(e => { console.log(e) });

    return data;
}

When I call this function to create a JSON object like so当我调用这个 function 来创建 JSON object 像这样

const beachData = getPlaces("beaches", lat, lon, clientID, clientSecret, versionDate);

It then returns as this:然后它返回如下:

Promise { <pending> }

I tried this with the same result我尝试了同样的结果

const beachData = getPlaces("beaches", lat, lon, fourSquareClientID, fourSquareClientSecret, versionDate).then(({ beachData }) => { beachData; });

Any guidance on what i'm doing wrong would be HUGELY appreciated.任何关于我做错了什么的指导将不胜感激。 If I'm not totally off the mark I'd like to be able to call on this function a few times and get some JSON objects back I can later combine for the response back to the front end.如果我没有完全偏离主题,我希望能够多次调用这个 function 并获取一些 JSON 对象,我稍后可以将响应组合回前端。 Thanks!谢谢!

If you try to log the return value of fetch ;如果您尝试记录fetch的返回值;

let x = fetch(URL);
console.log(x);

You would get:你会得到:

Promise { <pending> }

So the solution is of course to await it:所以解决方案当然是await它:

let x = await fetch(URL);

Similarly, you need to await your function:同样,您需要await您的 function:

const beachData = await getPlaces("beaches", lat, lon, clientID, clientSecret, versionDate);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM