Is there a way for me to come back after all child http requests have finished within a parent http request?

I am currently utilizing an API that provides detailed information on kills in a game. The initial endpoint returns an ID for the kill event, followed by a second endpoint to retrieve the names of both the killer and the killed player.

Due to the structure of this API, I need to first request the event ID and then wait for all IDs in the returned array to fetch results before processing the entire kill array:

    requestify.get(url).then(function (response) {
        var events = [];
        if (response.body && response.body.length > 0) {
            data = JSON.parse(response.body);
            if (data.hasOwnProperty('events')) {
                events = data.events.map(function(event) {
                    return this.getDataForHeroKillId(event.id, function(killInfo) {
                        return { killer: killInfo.killer, killed: killInfo.killed, timestamp: event.time };
                    });
                }.bind(this));
                console.log('events is: ', events);
            }
        }
        return Promise.all(events);
    }.bind(this));

The getKillInformation function is structured as follows:

KillFeed.prototype.getKillInformation = function(id, cb) {
var data = null;
    requestify.get(url).then(function (response) {
        var event = {};
        if (response.body && response.body.length > 0) {
            data = JSON.parse(response.body);
            if (data.hasOwnProperty('Killer')) {
                event = { killer: data.Killer, killed: data.Killed};
            }
        }
        cb(event);
    });
};

In my attempt with the second method, I intended to callback the result of each individual request, and once they had all been executed, the new array would hold the data. However, due to the asynchronous nature of JavaScript, my code block continues to return an empty events array. This non-blocking behavior is understandable, as blocking the event queue while making an HTTP request is not ideal. How can I address this issue?

Answer №1

To achieve this, one can utilize promises.

requestify.get(url).then(function (response) {
    var events = [];

    if (response.body && response.body.length > 0) {
        var data = JSON.parse(response.body);
        if (data.hasOwnProperty('events')) {
            // Processing the kill information begins here
            events = data.events.map(function(event) {
                return this.obtainKillInfo(event.id).then(function(killInfo) {
                    return { killer: killInfo.killer, killed: killInfo.killed, timestamp: event['time1'] };
                });
            }.bind(this));
        }
    }

    return Promise.all(events);
});

KillFeed.prototype.obtainKillInfo = function(id) {
    var url = 'internal_url';
    return requestify.get(url).then(function (response) {
        if (response.body && response.body.length > 0) {
            var data = JSON.parse(response.body);
            if (data.hasOwnProperty('killer')) {
                return { killer: data.Killer, killed: data.Killed };
            }
        }
    });
};

Answer №2

One option is to utilize the async library with its waterfall method. Although primarily a NodeJS module, it can also be adapted for use in the browser.

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

What is causing this setInterval function to run repeatedly?

Below is the code snippet from my Vue application: mounted: function () { this.timer = setInterval(async () => { if (this.progress >= 1) { this.progress = 1 clearInterval(this.timer) } console.log('update& ...

Tips for sending a MySQL parameter

Hey there, I need some help with the trigger setup I have: CREATE TRIGGER `update` AFTER UPDATE ON `table 1` FOR EACH ROW INSERT INTO table 2 ( Id, Revision, Purpose, Change ) VALUES ( OLD.Id, OLD.Revision, OLD.Purpose, @purpose_change /* user variable ...

The HTML must be loaded prior to the execution of my JavaScript function

In the controller, there is a function that sets the true value to a variable. function setShow() { return this.isShow === 'Foo'; } The value of this.isShow is set to 'Foo' Within the template, there is <div ng-if = "vm.setShow( ...

Manage and display data in Vue.js using the CLI

I'm currently developing a form where users can input data and I need to display that data on another page using Vue.js Below is the form I have created: <form id="main-contact-form" class="contact-form r ...

Introducing a new feature in React-Select: enabling copy-paste functionality for the multi-select text

Incorporating a react-select component (specifically generated using CreatableSelect) into my project has been quite beneficial. This multi select text input feature allows users to conveniently add keywords as options. While the current functionality is ...

Converting CSV data into JSON format using NodeJs and integrating it with MongoDB

Here is how my CSV file is structured: "Some Comment here" <Blank Cell> Header1 Header2 Header3 Value1 Value2 Header4 Value3 Value4 I am looking to convert this into JSON format and store it in MongoDB as follows: Obj: { Key1: Header ...

What is the best way to incorporate an exception for the printThis() element?

Is there a way to exclude a specific div from being printed when using the printThis() function? For example: <div id="print-it"> <div>hello</div> <div id="no-print-this"> <button>must be show on page but not print</but ...

Utilizing an Ajax call within "for" loops can result in skipping either odd or even iterations

Seeking assistance because we are facing a challenge that we cannot seem to overcome. Despite researching on platforms like StackOverflow and search engines, implementing a solution or solving the problem remains elusive. The goal is to develop a JavaScri ...

Adjust the size of an image post-render with the help of Angular or jQuery

Below is my current HTML code: <img width="150" height="150" src="https://d.pcd/image/578434201?hei=75&amp;wid=75&amp;qlt=50,0&amp;op_sharpen=1&amp;op_usm=0.9,0.5,0,0" ng-src="https://d.pcd/image/578434201?hei=75&amp;wid=75&amp; ...

Transforming Uint8Array into BigInt using Javascript

I've come across 3 different ways to convert a Uint8Array to BigInt, but each method seems to produce varying results. Can someone clarify which approach is correct and recommended? Utilizing the bigint-conversion library. The function bigintConversi ...

`Only firing event listener once`

I have created a JS module where I am adding a click event to all links that match a specific selector. Here is an example of how it's done: var Lightbox = (function () { var showLightbox = function () { // this does stuff }; var init = fu ...

Search field in DataTables appears to be misaligned

I'm in the process of developing a small website using JSP and DataTables (currently only for the first table). Here's what I have so far: As you can observe, there seems to be an alignment issue with the search field position. I'm n ...

Changing the data type of a column in an Excel file from XLSX to

I am currently working with the XLSX npm package and attempting to download a sample Excel file, add some data to it, and then upload it back. The fields in the file include MOBILE NUMBER, DATE, TIME, and NAME. When I upload the file, the values for the DA ...

Using JavaScript to Parse JSON with Carriage Returns and Line Breaks

Utilizing the script below in JavaScript, I am able to extract a JSON string from a different JS file: // code to retrieve JSON data from another JS module var jsonMatch = data.match( /\/\*JSON\[\*\/([\s\S]*?)\/&bso ...

Effortlessly sending information to the Material UI 'Table' element within a ReactJS application

I have integrated a materialUI built-in component to display data on my website. While the code closely resembles examples from the MaterialUI API site, I have customized it for my specific use case with five labeled columns. You can view my code below: h ...

Choose a specific example using the class name in nicEdit

Is there a way to select an instance using nicEdit based on its class name rather than just its id? For example: <div class="myInstance1"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed magna dolor, faucibus ac, iaculis non, cursus et ...

What is the best way to access the form button inside a div element?

Here is the code snippet for my form: <form accept-charset="utf-8" action="https:example.com" method="get" name="test"> <div class="classy"><input type="button" class="buttonE ...

The click function is only functioning for the most recently added div, failing to work on all previously appended divs in jQuery

Thank you to all the individuals who take the time to read my post and provide assistance. I am currently working on a select picker that displays the selected options below the select using ajax. However, I have encountered an issue where the 'x&apos ...

To access the link, simply click once if there is no child menu. However, if there is a child menu attached, be sure to click

I am working on a mobile menu that is designed to slide out when clicked. Currently, the parent pages are displayed by default. I want to implement functionality where if a parent page has child pages, clicking on it will slide down the sub menu. If click ...

Navigating forwards in Angular 7 causes loss of state

I have a situation with my angular 7 Ionic application. When I navigate to a page, I use the following code snippet: navigateToDetail(entity: User) { const navigationExtras: NavigationExtras = { state: { entity, entityId: entity.id ...