Invoking a function within a for loop in JavaScript

Here is the loop I am currently using:

if (list.length) {
        for (let i = 0; i < list.length; i++) {
            let fruit = list[i].attributes;
            if (fruit.color === 'red') {
                id = fruit.id;
                fruit.path = base.fruit_directory + "/" + id;
                saveFruit(id);
            }
        }
}

I have noticed that even though a red fruit is encountered in the loop, the function to save the fruit is not executed immediately. Can anyone explain why this might be happening?

Is there any way to work around this issue?

Answer №1

Suppose the function saveFruit returns a promise (if it doesn't, please share that specific function):

Promise.all(
  list.map(item=>item.attributes)// converting each item in the list to fruit
  .filter(fruit=>fruit.color==="red")// filtering only red fruits
  .map(f=>saveFruit(base.fruit_directory +"/"+f.id))//mapping each fruit to a promise resolving with response
).then(
  responses=>console.log("received responses:",responses)
)

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

Error: The function seems to be malfunctioning or missing

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script> <script type="text/javascript"> $('div'); // <--- THIS DOESN'T WORK </script> An issue has been encountere ...

Blazor, the Razor Library, npm, and webpack are essential tools for front

Let me try to explain this clearly. I have a Blazor WebAssembly (WASM) project that is referencing a Razor library without any issues. The Razor library successfully compiles a JavaScript bundle using webpack. One of the components I am attempting to creat ...

Looking for a specific value in a switch case code written in JavaScript

Below is the code snippet found in my alert box or any variable. I need to update the values in product to different values such as 'Tremfya', 'Remicade', dynamically. These values are required for a specific product like "linename" and ...

The functionality of event.charCode is ineffective in Firefox

I'm in a dilemma with restricting my text field to only accept numbers. Currently, I have the following code snippet: onkeypress="return (event.charCode >= 48 && event.charCode <= 57)" The issue arises when I attempt to delete (using b ...

Creating dynamic HTML tables within Highcharts

I need assistance with a webpage I'm working on where tables are dynamically added and removed using checkboxes in HTML. Essentially, when a checkbox is checked, a table is added, and when it's unchecked, the table is removed. My goal is to displ ...

develop a customizable component library similar to shadcn for easy installation

Currently in the process of developing a design system, I am looking for advice on creating an installable library similar to shadcn. It is important to me that the source code of the components can be easily accessed and modified within my project. Is t ...

PHP session does not refresh

There seems to be an issue occurring with my session. Here is the PHP code snippet I have been testing: public function updateTable() { $data = $this->getData(); $json_data = array( "recordsTotal" => intval($data[' ...

Avoid displaying duplicate values when using Ng-repeat in Angular JS

I'm in search of a method to prevent the display of duplicate values when using ng-repeat with Angular JS. Here is an example of my JSON list: [ { "Country":"Algeria", "Value":"200" }, { "Country":"France", "Value":"300" }, { "Country":"France", "Va ...

Event submission does not activate on mobile devices when the keyboard is displayed

When using Jquery 1.11.1, I send an ajax request on form submission: ... contactForm.on('submit', function(e) { e.preventDefault(); $.ajax({...}); ... The ContactForm comprises of an input text, a textarea, and a submit button. While in de ...

Using middleware to interact with BigQuery API Client and accessing secrets.json files

I am exploring the idea of utilizing a secrets folder to securely store my BigQuery API client secrets JSON file and leveraging the BigQuery client library for Node.js to execute queries on the database. However, the documentation seems to focus on loading ...

Activating the event trigger button by clicking on it

I have been utilizing the react-graph-vis package as shown below: <Graph ref={graph} graph={data} options={options()} events={events} /> The event prop triggers when I click on the graph element and the events functio ...

what is the best method to schedule tasks at a specific time in node-schedule?

I am facing an issue with running a node task daily at 8AM using the node-schedule package https://www.npmjs.com/package/node-schedule. Instead of running every day at 8AM, it is currently running every minute. What method should I use to correctly configu ...

how to use an object as a key in the groupBy function with underscore.js

My JSON structure is as follows: I am attempting to group by NodeGroup using the underscore library. vm.populatedNodeGroups = _($scope.nodes).groupBy(function (o) { return o.NodeGroup.Name; }); Within vm.populatedNodeGroups, ...

Is there a way to extract data within xml tags with attributes using JavaScript/ Ionic without relying on DOM or ActiveXObject?

I am trying to extract specific information located between two tags, specifically <wsse:BinarySecurityToken> Here is an example: <wsse:BinarySecurityToken att1="abc" att2="cd3" att3="adfa">This is the text I am trying to extract!!!</wsse ...

Guide to dynamically assigning the id attribute of an HTML element using angularjs (1.x)

Given an HTML element that is a div, what is the method to assign a value to its id attribute? The value should be a combination of a scope variable and a string. ...

React App folders are not being properly installed through NPX

Encountering an error message while attempting to use npx create-react-app Husna@LAPTOP-LPCC954R MINGW64 ~/Desktop/React GitHib Project (master) $ npx create-react-app github2020 Creating a new React app in C:\Users\Husna\Desktop\Reac ...

Having trouble with unblocking the UI using $.unblockUI()?

I have been developing a simple modal using blockUI that appears and asks the user to confirm their age. To avoid conflicts, I always create a separate page for each code I work on. However, the current html/javascript page I created is not working as inte ...

Achieving the functionality of making only one list item in the navbar bolded upon being clicked using React and Typescript logic

Currently, in my navigation bar, I am attempting to make only the active or clicked list item appear bold when clicked. At the moment, I can successfully achieve this effect; however, when I click on other list items, they also become bolded, while the ori ...

Preflight error: Requests blocked due to cross-origin restrictions

Hey, I'm really struggling with understanding cross origin requests. Here's the code snippet that's causing me trouble: Here is my JavaScript code: var config = { headers: { 'Access-Control-Allow-Origin&a ...

Passing props through Link in React can be a tricky process, especially when encountering issues with undefined props like this

My latest project involves creating a recipe research tool in react. The homepage features buttons that allow me to search for recipes and view them based on the data I gather. However, when I try to access the state values using 'console.log(this.pro ...