Generating multiple JSON objects in ExpressJS using a helper method

I've been attempting to generate multiple JSON objects by making an external call to the FourSquare API with different query parameters. However, my code is continuously returning a successful response code without any readable results. Here's the code snippet I'm trying to implement:

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

Every time I invoke this function to create a JSON object like so

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

The output appears as:

Promise { <pending> }

I also attempted using the following code with similar results

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

If anyone can provide some guidance on what might be going wrong, it would be greatly appreciated. Ideally, I'd like to be able to call this function multiple times and receive several JSON objects that I can later combine for the front end response. Thank you!

Answer №1

When logging the return value of the fetch function;

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

The output would be:

Promise { <pending> }

To resolve this, you should definitely use the await keyword:

let x = await fetch(URL);

Likewise, make sure to add the await keyword for your function call:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging jquery within an XML document in a SAPUI5 fragment

I'm experiencing a minor issue with my app. I have an Image property that has an empty background, and I want to add a class to it when clicked. However, my controller is unable to detect classes or IDs of properties in the view.xml document. Is there ...

Repeating single records multiple times in AngularJS with ng-repeat

I've been working on a project using AngularJS and have encountered some strange behavior with ng-repeat. My controller is returning data to ng-repeat as follows: ..... //Other JS Functions ..... var app = angular.module('main', ['ngTa ...

Upon concatenation, the screen automatically returns to the beginning of the page

I've set up a page with a list of items, and at the bottom there's a handy "Load more" button that fetches new items to add on top of the existing list: handleLoadProducts = (append = false) => { this.setState({ isLoading: true, ...

JavaScript onclick event ceases to function after initial click

I am currently working on designing a custom selection menu using HTML, CSS, and JavaScript. The concept is simple: there is a div element styled to look like an input field that, when clicked, reveals another div containing a list of options. The user can ...

Converting req.body to match database columns using ES6 model in Knex JS - Simplified Approach

I'm currently working on a project using node js with es6. I have a table with several fields and I'm utilizing knex js for query building and db management. My question is how can I initialize the fields by passing req.body object to the es6 cla ...

A Guide to Parsing JSONArray in Android

How do I handle parsing a JSONArray from a webservice response that is structured like this: <?xml version="1.0" encoding="UTF-8"?> <string xmlns="http://www.somewebsite.com/"><PricingTier ANo='01234567' MsgFlg=''>& ...

Retrieving the data payload from a 400 response using HttpURLConnection

When making a JSON request to my web service, I return a 400 message code with a detailed JSON error response if the request is bad. But how can I retrieve this payload on the client side using HttpURLConnection? The connection's InputStream is null a ...

Transferring Client Files to Azure Blob Storage using MVC Framework

After setting up a WebApp(MVC4) with a file upload feature, I made a major error by allowing clients to upload files directly to my server (Virtual Machine Azure). To make this work, I adjusted the following settings in my WebConfig: maxRequestLength="2 ...

Best method to ensure file upload completion (Using Mongoose)

Currently in the process of developing an application using React and Mongoose (MongoDB) where I am uploading a text file containing over 9000 lines of JSON data. Each line holds significant value and needs to be stored in the database for future access. ...

Checking the validity of subdomain names using JavaScript/jQuery

For users signing up, my form allows them to choose a subdomain for their account. The valid characters allowed in the subdomain are letters, numbers, and dashes. Spaces and most special characters should be filtered out. http://_________.ourapp.com To r ...

What is the best way to display the panel during a postback?

I have a group with two radio buttons labeled purchase and expenses. When the purchase radio button is clicked, the panelpurchase will be displayed, and similarly, the panelexpense will show for the expenses radio button. Check out the image of the output ...

"Despite modifying the ID in the response data of Angular MongoDB, the request data ID remains unchanged

Having trouble with managing requests and responses, specifically when a customer tries to add multiple items of the same product but in different sizes. The initial step involves checking if the ID exists by using a count and an if statement. If it exists ...

I'm having trouble understanding why I can't access the properties of a class within a function that has been passed to an Angular

Currently, I have integrated HTML 5 geolocation into an Angular component: ... export class AngularComponent { ... constructor(private db: DatabaseService) {} // this function is linked to an HTML button logCoords(message, ...

Draggable vue includes a Textarea HTML element that allows users to easily

The issue lies in implementing the draggable functionality on a textarea element. While the textarea allows text input and deletion, trying to select the text using pointer events triggers the dragging function instead, as shown in the image below: https ...

Using Java's Jackson streaming API to establish a connection using TCP sockets

Having trouble with sending and receiving JSON objects over a socket connection. The parsing is not working correctly on the server side. This project marks my first attempt at Java programming. Below is my socket class: static class CheckerSocket im ...

Convert a portion of an object into a string to send in a server request

I have customized the fetch method of a Backbone Collection to make a request to a different URL under certain conditions, and I need to include some data with it. The modified fetch method (which I obtained from another solution on Stack Overflow) is as f ...

Building a web proxy with node.js and express

I'm currently in the process of designing a personalized web proxy using JavaScript to allow users to surf the internet through a designated website, similar to this . One challenge I encountered is transferring the response from a URL back to the us ...

Tips for incorporating a title and script into a Vue template using Nuxt.js

Looking to enhance your website's SEO by adding title, description, and other HTML meta tags? Wondering how to achieve this in a Vue template? For instance, let's say you want to include the meta tags in your template.vue file. Additionally, y ...

The ngModel controller did not trigger the $$updateEventHandler function

Currently in the process of transitioning the development environment from gulp to webpack for a hybrid app that does not use AngularJS and React. The application is quite large, currently consisting of 10mb worth of files. However, I have encountered an ...

Displaying information easily with Angular's ngGrid

I'm a beginner to Angular and my knowledge of JavaScript is limited. I'm encountering an issue while trying to display data in ngGrid with the code below. Can you help me identify what's causing the problem? Essentially, I am fetching data ...