Updating the value in an array of objects simultaneously using JavaScript asynchronously

I've encountered a problem that has been raised before, and despite trying various solutions such as using .map or (function(post){ async })(value), I'm still unable to move forward...

Here's the scenario: I have an array of objects along with a for loop:

var postsData = [{thumbnail: www.website.com/image.jpg}, {thumbnail: www.website.com/image.jpg}, {thumbnail... etc}];

for (let i = 0; i < 3; i++) {
  let thumbnail = postsData[i].thumbnail;
  Cloudinary.uploader.upload(thumbnail, function(result){
    // Feeling lost here
    // The result is returning as an object, and my goal is to update each thumbnail in
    // the postsData array to be result.public_id
  }, {transformation:[{}]});
} // Loop through all items in the array

// Figure out what to do next with the "updated" postsData array

An illustrative example would greatly aid in grasping the concept, especially since dealing with altering values requires handling asynchronous functions.

Answer №1

Modify the "thumbnail" attribute of an object in an array to be equal to result.public_id. Implement a function that requires the current object from the postsData array as a parameter, update the "thumbnail" attribute using the upload function with the help of the Function.prototype.bind() method.

var length = postsData.length;
var count = 0;

function processData(response, element) {
  element["thumbnail"] = response_public.id;
  if (++count === length) finish(postsData);
}

function finish(array) {
  console.log(array, postsData);
}

for (let element of postsData) {
  Cloudinary.uploader.upload(
    thumbnail
    , processData.bind(null, element)
    , {transformation:[{}]}
  );
}

Check out the plnkr example here

Answer №2

To my understanding, you seem to be attempting to iterate through an array and perform asynchronous functions on each element. My suggestion would be to utilize Promise.js (refer to enter link description here). Here is a rough draft of how the code could potentially appear:

// initialize an array to hold promises
const PromiseArr = [];
postsData.map(d => {
  PromiseArr.push(
    // execute async actions and add them to the array
    new Promise((resolve, reject) => {
       Cloudinary.uploader.upload(thumbnail,(result) => {
         // return the result
         resolve(result);
       });
    })
  );
})
// execute all async actions and save the results in the result array
const result = PromiseArr.all();

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

React - assigning a value to an input using JavaScript does not fire the 'onChange' event

In my React application with version 15.4.2, I am facing an issue where updating the value of a text input field using JavaScript does not trigger the associated onChange event listener. Despite the content being correctly updated, the handler is not being ...

Encountering path import errors when developing a sample webpack site within a TypeScript library

Struggling to integrate my custom library with TypeScript and Webpack. Import errors are causing headaches, despite smooth sailing in CLion. Running tsc within the project directory is error-free, unlike when running npm run dev in the examples/webpack di ...

Tips for correctly sending headers with SWR requests?

I've made the decision to transition the majority of my API functions to SWR because of its enhanced capabilities! Issue at Hand However, I'm encountering a major problem trying to pass headers properly into SWR. Despite consulting the documenta ...

listening for new messages on discord using a loop in discord.js

My Discord.js bot is experiencing an issue where the callback function for the "message" event is not triggering inside a loop in my code, despite working correctly everywhere else. I've tried using console.log statements for debugging but haven' ...

Sending an array and an object simultaneously through a single ajax request

I previously inquired about passing an object to an ajax request for my rest service. Now I am wondering if it's possible to pass both an array and an object within a single ajax request. Any insights on this matter would be greatly valued. ...

Is it possible to use the same HTML select/dropdown menu for multiple rows in a table?

I am working with an HTML table that usually has between 10-30 rows, each containing a column for "item name". The drop down menu consists of about 75 products to choose from. In order to reduce the page size, I want to use a single drop down list for all ...

Tips for highlighting a button within a details list using React and Office Fabric

Does anyone have any tips on how to focus a button in React DetailsList? I've been considering using refs and attempting something like this: findDOMNode<HTMLButtonElement>(this.refs.mybutton).focus() However, I've encountered dif ...

Sending a properly formatted string on Postman

My website allows users to answer coding problems. I am looking to store the questions and answers in a mongodb database. However, when testing the routes on my express application, I am encountering difficulties in sending formatted text in the request to ...

Exploring the contrast of utilizing the `new Date()` function compared to Firestore's `new

I am developing a new app and need to calculate the time elapsed between the start and end of a run. When the run starts, I record a timestamp using the new Date() function in Firebase. (I opted for this over firestore fieldValue to avoid conflicts with o ...

Using Javascript to extract information from the div element

Within my HTML code, I have a total of 4 <div> tags and a corresponding <a> tag for each of these <div> tags. Inside each div tag, there are 2 span tags and an additional a tag. Upon clicking the a tag, I aim to extract the product name ...

Updating the label on a Highcharts speedometer gauge

I need to customize the number sequence of a speedometer displaying internet bandwidth speed. I have done extensive research but haven't found a solution yet. Below is the code snippet for the highchart gauge. The current label sequence is 0,10,20,30 ...

Access a specific JSON value using AngularJS

When using AngularJS to read a specific JSON value, I encountered the following issue: $http({method: 'GET', url: urlVersion}). success(function(data, status, headers, config) { console.log("success data " + status); $scope.ext = data.ve ...

On what occasion is a DOM element considered "prepared"?

Here's a question that might make you think twice: $(document).ready(function() { }); Sometimes, the simplest questions lead to interesting discussions. Imagine having a list of elements like this: <body> <p>Paragraph</p> < ...

Attempting to allocate arrays to an entity and then allocate it to a div

As a newcomer to the world of programming, I find myself struggling with a specific task. Let me explain: I have an SVG map of Canada that consists of 12 provinces, each identified by a unique ID. My goal is to assign a minimum age requirement to each pro ...

Ways to obtain a list of properties for an object

I have a collection of items, each item containing various attributes including a list of related elements: { name : 'Club 01' , id : 1 , form : 45 , points : 0 , tactics : 'neutral' , played : ...

Transform data from API arrays into a remapped object with updated keys and structure

I received the following output from my return object: { data: [ { ts: "20-10-26", events: 1500, }, { ts: "20-10-27", events: 1280, }, { ts: "20-10-28", events: 1111, } ] } T ...

Creating with NodeJS

I'm encountering an issue where my code is not waiting for a response when trying to retrieve data from a database. The connection is fine and everything works well, but Express isn't patient enough for the data to come through. Despite trying v ...

There seems to be a problem with the Bootstrap Container and Container Fluid

I am currently utilizing Bootstrap 3.3.7 and have incorporated buttons to enhance the content on my webpage. Upon using container-fluid, I noticed that it does not expand the content across the entire page but rather confines it to the center area of the ...

Accessing the identical file concurrently through ajax 12 times

I'm facing an issue with loading the same external file multiple times on a page. When the page loads, it takes up to a minute due to large load times. I've tried using Ajax to load each file individually, but running a loop to load all files at ...

Tips for adapting this code to be compatible with react-router v6

Within ProtectedRoute.js, the following code is implemented: const ProtectedRoute = ({ component: Component, ...rest }) => { const { loading, isAuthenticated, user } = useSelector((state) => state.user); return ( <Fragment> {!load ...