Having Difficulty Configuring Async Request Outcome

I'm struggling to access the outcome of an asynchronous request made to an rss feed. After reading a post on How do I return the response from an asynchronous call?, which recommended using Promises, I tried implementing one. However, even though the Promise resolves, I still cannot access the result of the request outside of the function.

I've been trying to assign the variable film to the request result, but it always ends up being undefined.

var request = require("request");
var parseString = require("xml2js").parseString;

var url = 'http://feeds.frogpants.com/filmsack_feed.xml';

var film;

request(url, function(error, response, body) {
    return new Promise(function(resolve, reject) {
        if (error) {
            console.log(error);
        }
        else {
            if (response.statusCode === 200) {
                parseString(body, function(err, result) {
                    var feed = result.rss.channel[0].item.reduce(function(acc, item) {
                        acc.push(item);
                        return acc;
                    }, [])
                    resolve(feed)
                })
            }
        }
    })
    .then(function(data) {
        film = data;
    })
})

console.log(film)

When I log feed within the request function, it returns the desired results. What could I be missing here? Thank you for any insights.

Answer №1

I may not have a lot of experience, but it seems like the problem here is that console.log is being called before your asynchronous request returns any data. One possible solution could be to return "film" from the last then() function and then add another then() function to handle logging that variable.


    ...    
    .then(function(data) {
        return film = data;
    })
    .then((result) => console.log(result))
})

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

Utilizing object UUID keys to associate products in VueJS

Hey there, I've gone ahead and created an object with UUIDs but now I'm looking for a way to link these UUIDs to specific items. It seems like there needs to be some separation between the UUID and the rest of the object, however, my main issue i ...

Create a way to allow users to download html2canvas with a customized filename

I have a div where I want to use html2canvas to save a PNG file of its content. The issue is that the name of the saved file is static in my code and does not change unless I manually edit it. Is there a way to dynamically set the filename based on user i ...

Incorporating post data into a Partial View

Main objective: My goal is to enable users to click on a specific day on the calendar plugin and have a popup Bootstrap modal display events scheduled for that day. Current Progress: I am currently utilizing a javascript plugin called fullCalendar. With ...

The function passed to the modal is not functioning correctly when stored within the state

Is it possible to create a unique modal that can be utilized for multiple actions on the same page? To achieve this, I have implemented a state to store the title, description, and submit function for modal click and modal open state. In addition, I want t ...

Error: Express is undefined and does not have a property called 'use'

I'm encountering a problem with my express server specifically when I utilize the 'app.use' command. Within my task-routes.js file, the following code is present: import express from 'express'; const router = express.Router(); ...

Retrieve the current language from a non-page component on the server side with the help of Next.js and the next-i18next

I am working on a nextjs application that utilizes the next-i18next library for internationalization. I'm struggling to figure out how to access the current language on the server-side within a component that is not a page. On the server side, you ca ...

Troubleshooting a Codeigniter issue with CSRF and jQuery ajax

Having trouble with posting data using ajax? I keep running into an error related to CSRF and despite my efforts, I have not been able to find a solution. Can someone please assist me with this issue? Here is the error message I am consistently receiving: ...

Utilizing the loop counter within an Array

Currently, I am attempting to iterate through numbers 1 to 21 and then utilize those numbers in order to obtain an Array of Strings like ['e1.wkh',...'e21.wkh']. However, at the moment I am only receiving the value ['e21.wkh'] ...

Is there a different method similar to Textfield onChange that works like the HTML onChange attribute?

In my current setup, I have a Textfield component nested within other components where I pass a function pointer down to it as a prop. The challenge I'm facing is that the function responsible for passing the contents of the Textfield back up to the r ...

Ways to obtain data in JavaScript function from HTML

Struggling to pass the key from a database query in HTML using PHP to a JavaScript function? You're not alone. The challenge lies in passing the field_id to the updateRecords() JS function through the onClick() event of an HTML button. Previously, se ...

bootstrap modal dialog displayed on the edge of the webpage

I am facing an issue with a modal dialog that pops up when clicking on a thumbnail. The JavaScript code I used, which was sourced online, integrates a basic Bootstrap grid layout. The problem arises when half of the popup extends beyond the edge of the pa ...

How come lazy loading isn't functioning in my React project?

Check out my project: link. This project includes routers and lazy-loaded components for each page. Here's a brief example of a router component: export const RoutersComponent = () => { return ( <HashRouter basename={'/'}> ...

What could be causing VueJs2 computed properties to not update?

Check out this updated grid example from the official examples. In my application, I need to reposition the sortOrders array. created: function () { var vm = this; this.columns.forEach(function (key) { vm.sortOrders[key] = 1 }) ...

Tips on how to transform an <input type="text"> element into a <tr> element using jquery

I am currently working on updating a row using jQuery Ajax. Whenever the Edit button is clicked, it switches the <tr> element to <input type='text'>. I have utilized the .Change method which triggers successfully, but my goal is to r ...

Converting JSON data into a JavaScript array and retrieving the array through an AJAX request from PHP

Currently, I am working on a project where I have created a function named AjaxRequest to manage all my AJAX requests. While making the requests is not an issue, receiving and placing the data back onto the page has proven to be quite challenging. Within ...

Having trouble reaching an element within a successful Ajax call

I have encountered an issue where the element is not being recognized when putting an ajax call inside another ajax call. Here is an example of the code: $.ajax({ url: 'controleFatAcoes.php', type: 'post', dataType: 'h ...

How to update router query in Next JS without triggering a page change event

I am seeking a solution to modify a URL query for the current page in Next JS without causing the page change event to trigger. Specifically, I need to be able to remember the week that is being viewed in a calendar, much like how Google Calendar operates. ...

NodeJS is capable of handling a limited number of requests at a time

Utilizing jQuery to send requests to a local server has been causing some issues. After sending approximately 4-7 requests, the port stops working without any visible error. Eventually, after a few minutes, some of the requests are successfully sent to the ...

Where can I find the @types for a specific lodash package?

Seeking to utilize a specific function from lodash - assignin. I have successfully installed lodash.assignin and incorporated it into my project: import assignIn = require('lodash.assignin'); However, when compiling, an error occurs: "error TS2 ...

Updating ng-src in Angular with image URL from factory/controller promise

Within my application, there is a controller responsible for capturing user input in the form of a Twitter handle. This input is then passed to a factory, which sends it to the backend code to make API calls and ultimately retrieve an image URL. Although ...