The Parse database retrieval process is not receiving complete results from the HTTP request

Within my application's Parse Cloud Code, I have created a job with the following code:

Parse.Cloud.job("requestLocations", function (request, response) {Parse.Cloud.httpRequest({
    url: 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=29.7030428,-98.1364808&radius=900&types=restaurant&key=AIzaSyCTg0x68Q6lrCAo6-A37zkxge81jDEKpvo'
}).then(function (httpResponse) {
    // Success
    response.success("Success");
    var parsedData = JSON.parse(httpResponse.text);
    var Location = Parse.Object.extend("Locations");

    for (var i = 0; i < parsedData.results.length; i++) {
        var restaurant = new Location();
        var placeId = parsedData.results[i].place_id;
        var name = parsedData.results[i].name;
        var vicinity = parsedData.results[i].vicinity;
        var point = new Parse.GeoPoint({
            latitude: parsedData.results[i].geometry.location.lat,
            longitude: parsedData.results[i].geometry.location.lng
        });

        restaurant.set("placeId", placeId);
        restaurant.set("name", name);
        restaurant.set("vicinity", vicinity);
        restaurant.set("location", point);
        restaurant.save(null, {
            success: function (location) {
                console.log("Object ID: " + location.id);
            },
            error: function (location, error) {
                console.log("Failed to create object, with error code: " + error.message);
            }
        });
    }
}, function (httpResponse) {
    // Error
    response.error('request failed with response code ' + httpResponse)
});});

The HTTP request in this function is meant to return a total of 14 places, however, only 9 places are being returned and the selection seems inconsistent. It appears there may be an issue with how the function is structured. Any assistance in resolving this problem would be greatly appreciated. My goal is to retrieve as many locations as desired based on the radius specified in the HTTP request.

Thank You

Answer №1

Your http request is set up correctly, using a promise that resolves once the request is finished. However, the code within your then() block attempts to create multiple objects in a loop without waiting for them all to finish, ultimately failing to call response.success. To resolve this issue, follow these steps...

// Here's a function that breaks down the process of creating a Locations object from the http data

function locationFromResult(result) {
    var Location = Parse.Object.extend("Locations");
    var restaurant = new Location();
    var placeId = result.place_id;
    var name = result.name;
    var vicinity = result.vicinity;
    var point = new Parse.GeoPoint({
        latitude: result.geometry.location.lat,
        longitude: result.geometry.location.lng
    });
    restaurant.set("placeId", placeId);
    restaurant.set("name", name);
    restaurant.set("vicinity", vicinity);
    restaurant.set("location", point);
    return restaurant;
}

Parse.Cloud.job("requestLocations", function (request, response) {
    var url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=29.7030428,-98.1364808&radius=900&types=restaurant&key=AIzaSyCTg0x68Q6lrCAo6-A37zkxge81jDEKpvo';
    Parse.Cloud.httpRequest({url: url}).then(function (httpResponse) {
        var parsedData = JSON.parse(httpResponse.text);
        var locations = parsedData.results.map(function(result) {
            return locationFromResult(result);
        });
        // It's crucial to save all the new objects before proceeding
        // This can be achieved by saving each object individually or using Parse.Promise.when()
        return Parse.Object.saveAll(locations);
    }).then(function(result) {
        response.success(JSON.stringify(result));
    }, function(error) {
        response.error(JSON.stringify(error));
    });
});

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

Modal's ng-click not triggering component's function

I am currently working on resolving an issue. My choice to use AngularJS is intentional, as I prefer not to load the entire NPM of Angular. Additionally, we heavily rely on Razor Syntax for the Web Layer. Implementation in Create.cshtml file <button ...

Encountered a runtime error while processing 400 requests

Current Situation: When authenticating the username and password in my Ionic 2 project using WebApi 2 token authentication, a token is returned if the credentials are correct. However, a 400 bad request error is returned if the credentials are incorrect. ...

Use jQuery to locate the active class within a specific list item and then transfer that class to a different item within the

I have a pair of indicator lists for a bootstrap carousel First List: <ol class="rightci carousel-indicators"> <li class="active" data-target="#carousel-example-generic" data-slide-to="0" ></li> <li data-target="#carousel-example-g ...

Are there any known issues with Firefox, jQuery, and CSS animations working in tandem?

As I develop a website with jQuery to manage CSS class switching for animations, I have encountered a strange issue. While Google Chrome and Internet Explorer 9/10 work perfectly, Firefox (Aurora 24 and Firefox 23) does not perform the animations smoothly, ...

Discovering the method for retrieving JavaScript output in Selenium

Whenever I need to run JavaScript code, the following script has been proven to work effectively: from selenium import webdriver driver=webdriver.Firefox() driver.get("https:example.com") driver.execute_script('isLogin()') However, when I atte ...

Tips for creating a scrollable smiley input field

I have a chat system where I am incorporating smileys from a predefined list. QUERY I am looking to create a scrolling feature for the smileys similar to how it is implemented on this particular website. The twist I want to add is to have this functiona ...

Designing CSS elements that flow from top to bottom, left to right, and extend to the right when overflowing

I'm attempting to create a layout where divs are displayed from top to bottom, but once they reach the bottom of the browser window, any additional divs will overflow to the right. You can take a look at the desired layout here: https://i.stack.imgur. ...

Web-services integration in Unity with Dll files and seamless interoperability with .Net version 4.0

I'm currently facing an issue with using web services in Unity. I utilized svcutil to create a proxy class, but encountered the problem where the proxy class was relying on "System.Threading.Tasks." After realizing that System.Threading.Tasks is not ...

Transmit updated value to masterpage upon selection alteration

In my current project using ASP.NET, I have a MasterPage that includes a navigation bar with different options. One of the options leads to another page where the company now requires me to pass a parameter through the link. After some research, I managed ...

What steps can be taken to effectively build a test suite architecture using Jest?

After exploring all the available resources on the Jest documentation website, including various guides and examples, I have yet to find a solution to my specific question. I am in search of a methodology that would enable me to individually run test case ...

To iterate through a multi-dimensional array

I am facing an issue with fetching data within an array in the code below var str = "Service1|USER_ID, Service1|PASSWORD" var str_array = str.split(','); console.log(str_array) for(var i = 0; i < str_array.length; i++) { str_array[i] = st ...

Tips for aligning text in MUI Breadcrumbs

I am currently utilizing MUI Breadcrumb within my code and I am seeking a solution to center the content within the Breadcrumb. Below is the code snippet that I have attempted: https://i.stack.imgur.com/7zb1H.png <BreadcrumbStyle style={{marginTop:30}} ...

Every second, I am dynamically updating a section of my HTML and populating it with data retrieved from a database

Struggling to constantly update a section of HTML with data from a database? The code isn't functioning properly and I'm in need of some assistance. In the first part of the code snippet, an HTML page calls an update function that makes an ajax c ...

Ordering products in Angular JS based on whether they are free or not can be done by

I am currently implementing Angular's ng-repeat to showcase products from a JSON feed. My goal is to organize and categorize these products by distinguishing between free items (with the JSON property 'free':true) and those that require a pu ...

What is the best way to create a basic accordion using only certain table rows?

I am faced with the task of transforming a HTML table that lists various items. Each <tr> within the table contains a unique title element, but there are cases where rows can share the same title indicating their relation. My goal is to implement jQu ...

Enhance JSON readability in Python with elegant formatting

Seeking assistance from someone knowledgeable about prettifying JSON! Any help would be greatly appreciated! I am trying to convert a complex Python string into JSON format and then save it to a file using the following function: with open('data.txt ...

Is it possible to seamlessly alternate between JSON using the Jackson processor and XML using XStream, or is it feasible to use both formats simultaneously

I am in the process of developing a Web Server that can convert an Object into both JSON and XML formats. I have successfully used Jackson to serialize an object into JSON through my REST Interface, but I also need to support XML serialization. Recently, ...

Transition the background image into view upon hover

I'm looking to enhance my jQuery code that changes the background image when hovering over text by adding a fade-in effect. Here's the current code I have: $(document).ready(function(){ $("#anatomyNow").hover(function(){ $("#bg").cs ...

Navigational highlighting of current page section on a one-page website

I'm struggling with adding a navigation bar feature that will highlight the current section being viewed on my website. All I want is for the currently viewed section to appear bold in the navigation bar. Check out the codepen link: HTML <na ...

Troubleshooting JavaScript issues: jQuery not functioning as expected

Although I consider myself experienced in programming, my venture into jQuery has hit a roadblock with this seemingly simple code: $(document).ready(function() { $('.footer').click(function() { $('.footer').fadeOut('sl ...