Reorganizing responses in JavaScript using the Fetch API

Recently, I have been working with the fetch API in JavaScript. I encountered an issue where I have an array of months and need to retrieve values from a database. However, when logging the results in the console, the array of months gets rearranged. How can I prevent this reordering of arrays?

async function getMonthAccomplishment(m, s) {
    this.m = m;
    this.s = s;

    const param_point = 'filecase/monthaccomplishment/' + this.m + '/' + this.s;

    this.endpoint = url() + param_point;

    return await fetch(this.endpoint, {credentials: 'include'})
        .then((resolve) => {
            if(resolve.ok) {
                return resolve.text();
            }
        }, rejected => { console.error(rejected); })
        .then((response) => {
            return response;
        }).catch((error) => {
            console.error(error);
        });
}

let PostMonthAccomplishment = function() {
    this.m = '';
    this.s = '';
    this.t = '';
};

PostMonthAccomplishment.prototype.set = function(m, s, t) {
    this.m = m;
    this.s = s;
    this.t = t;

    if(typeof this.m === 'object' && typeof this.s === 'string') {
        this.m.forEach((month) => {
            getMonthAccomplishment(month, this.s)
                .then((data) => {
                    console.log(month + ': ' + this.s + ' -> ' + data);
                });
        });
    } else {
        console.error('invalid typeof!');
    }
};

const months = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];
const status = ['beginning+balance', 'case+receive', 'Decided/Report+&+Recom.+Submitted+from+Pending'];

let pma = new PostMonthAccomplishment();
pma.set(months, status[1], '');

Results may vary:

dar:27 january: case+receive -> 0
dar:27 april: case+receive -> 0
dar:27 may: case+receive -> 0
dar:27 march: case+receive -> 0
dar:27 june: case+receive -> 0
dar:27 february: case+receive -> 0
dar:27 july: case+receive -> 0
dar:27 august: case+receive -> 0
dar:27 september: case+receive -> 0
dar:27 october: case+receive -> 0
dar:27 november: case+receive -> 0
dar:27 december: case+receive -> 0

And at times:

dar:27 january: case+receive -> 0
dar:27 february: case+receive -> 0
dar:27 june: case+receive -> 0
dar:27 april: case+receive -> 0
dar:27 march: case+receive -> 0
dar:27 may: case+receive -> 0
dar:27 july: case+receive -> 0
dar:27 august: case+receive -> 0
dar:27 september: case+receive -> 0
dar:27 october: case+receive -> 0
dar:27 november: case+receive -> 0
dar:27 december: case+receive -> 0

Answer №1

To achieve sequential processing of tasks, you can easily use multiple lines with await statements to pass the output from one asynchronous call to another. This is a common practice when working with promises. Make sure to place your array data within an async function like the following example for handling parallel requests:

async function processArr(arr) {
  let pArray = []
  for(const item of arr) {
    let response = await fetch('https://jsonplaceholder.typicode.com/posts/'+ item)
    pArray.push(response.json())
  }
  const months = await Promise.all(pArray);
  console.log(months)
  return months
}

processArr([1, 2, 3])

p/s update for sequential processing:

async function processArr(arr) {
  let pArray = []
  for(const item of arr) {
    let response = await fetch('https://jsonplaceholder.typicode.com/posts/'+ item)
    let data = await response.json();
  }
}

processArr([1, 2, 3])

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

To retrieve the value of an element in the Response tab of the Network tab in Google Chrome's developer tools, I am looking to use JavaScript, TypeScript, or Cypress

Currently working on a cypress test case where I am struggling to fetch the requirement id value from results using JS/TS/Cypress. Unfortunately, I haven't been able to find a solution yet. I've come across various posts and articles, but none o ...

Display an alert in a React Native app using Native Base based on certain conditions

I am currently working on an alert component that utilizes a Native Base alert component function CustomAlert() { const { alert, setAlert } = useAuthContext(); const clearAlert = () => setAlert({ status: "", message: "" }); us ...

Discover the highest value within an array of objects, along with any numerical object attributes that have a value greater than zero

Considering an array of objects structured as follows: [{ "202201": { "WO": 900, "WS": 0, "SY": 0.915, "LY": 0.98, "CT": 75 }, "202202" ...

Transitioning from using .live() to utilizing the .on() method

I am facing an issue with my code that is responsible for drawing newly added comments. After switching from using live to on, the code does not work on elements added after the page has loaded. Below is the code in question: $(function(){ $('.s ...

Troubleshooting a JSON error encountered while utilizing the mongoimport tool

Currently, I am utilizing the mongoimport utility to import data from a json file into mongodb with the following command: mongoimport --db city --collection inspections ./city_inspections.json #mongo import utility The json data structure looks like this ...

Enhancing interactivity: Implementing a ripple effect for Card clicks in Material UI

I'm curious if there's a method to incorporate a ripple effect into Material UI's Card component when it is clicked. Additionally, I am wondering if it is achievable to have the ripple effect display on top of the content within the Card co ...

The effective method for transferring a PHP variable value between two PHP files using jQuery

I am looking to transmit the variable "idlaw" from base.js to the PHP page edit.php. modifyLegislation.php <input class='btn btn-primary buttonBlue' type='button' name='btnAcceptPending' value='Edit' onClick="ja ...

RegEx in JavaScript to identify and match the innerHTML property of all elements

I am currently in the process of developing a Chrome extension that needs to identify specific pages within a website, including the Log In / Sign In page, the Sign Up / Register page, the About page, and the Contact Us page. My approach involves obtainin ...

Customizing textfield error color in MUI5 React based on conditions

I am looking for a way to dynamically change the color of error messages in my application, with warnings displaying in orange and errors in red. I prefer not to use useStyle as it is now deprecated in mui5. Below is the code snippet I have created: import ...

Differences between the `getLocationAbsUrl` and `getCurrentUrl

When working with Protractor, there are two methods available in the globally accessible browser object: getLocationAbsUrl() This method returns the current absolute URL from AngularJS. getCurrentUrl() The getCurrentUrl() method schedules a co ...

Copy files using grunt, in accordance with the ant pattern, while excluding any variable directories

My task is to transfer files from the src/ folder to the dist/plugin directory. Since the version can potentially change, I would like to exclude the version number in all instances. Here is what I currently have: files[{ cwd: 'src' src ...

Deleting a dynamically generated row from an array

I have a setup with two textboxes and an add button. Whenever the add button is clicked, it creates a new row in a table underneath the textboxes. Each row in the table has its own Remove button. However, when I click on the remove button, the table row is ...

To include the express module in another JavaScript file, simply require it at the top of the file using the following code: `

Let me elaborate on my current project setup. I have integrated the express module in my app.js. Now, I need to access this module in other files such as index.js, admin.js, and gallery.js. However, I do not want to repeat the same code in each of these fi ...

Troubleshooting Webpack: Dealing with the error "React is not defined" in Bundle.js

Utilizing Webpack has allowed me to bundle all my npm modules efficiently. Take a look at my webpack.config.js setup: "use strict"; module.exports = { entry: './main.js', output: { path: __dirname, filename: 'bundle.js' }, ...

Efficiently loading an image in one go

Rendering approximately 3000 records, each row displays: Customer Profile Edit Customer Name, Action 1 John Edit image | Delete image 2 John Edit image | Delete image 3 John Edit image | Delete image 4 John ...

SCSS - Hide div1 when div2 is hovered over

In an attempt to make a div disappear when hovering over another div using only CSS, I have set up two divs: <div class="" id="target">I will disappear</div> <div class="hover_box">Hover me</div> Here is my SCSS code: #target { ...

Storing Data with expressjs/session in NodeJS

My development project involves 3 files: app.js, index.js (routes), and Users.js (controller). Upon successful user login (verification between POST data and the database), I aim to store information in a session using expressjs/session. Below is how I c ...

What is the best way to troubleshoot a Node.js backend using node-inspector?

Currently, I am in the process of debugging my backend code and I am uncertain if I am following the correct approach. The debugging setup I have implemented is as follows: Node 6.9.1 and node-inspector 0.12.8 Begin by opening a command prompt and exec ...

Implement a jQuery click event on a dynamically generated button in the code-behind

A button (Replybtn) is dynamically created when clicked in the code-behind file. --Default.aspx.cs-- protected void ReloadThePanelDetails_Click(object sender, EventArgs e) { litResultDetails.Text = litResultDetails.Text + "<button id='Replyb ...

Generate an image on Canvas using a URL link

I have a unique URL that generates canvas images with specific parameters. It functions properly when loaded in a browser. The final line of code is: window.location = canvas.toDataURL("image/png"); However, when attempting to use this URL from another ...