Following the completion of every asynchronous operation, a callback will be executed

I am facing a situation where I have an array of images that are uploaded with a series of asynchronous operations as shown below:

for ( let key in imageFileObject ) {
  const imageFile = imageFileObject[key]
  dispatch('get_signed_request', imageFile)
}

Every time the dispatch function is called, it triggers numerous other asynchronous operations.

My goal is to determine when all these operations have been completed so that I can proceed with further actions.

Is there a way to accomplish this?

Answer №1

Give this a try:

let remainingImages = Object.keys(imageFileObject).length;

for (var prop in imageFileObject) {
  const img = imageFileObject[prop];
  dispatch('get_signed_request', img).then((response)=> {
     remainingImages--;
     if(remainingImages === 0){
        // process complete
     } 
  });
}

An example you can run in the console to see it in action:

var asyncFunc = () => {
   return new Promise((resolve,reject)=> {
          setTimeout(() => { console.log("task completed"); resolve() },1000);
   });
}

let tasks = [asyncFunc, asyncFunc, asyncFunc];

let totalTasks = tasks.length;

for (let task of tasks) { 
  task().then((result)=> {
     totalTasks--;
     if(totalTasks === 0){
        console.log("all tasks finished");
     } 
  });
}

Answer №2

In the case that imageFileArray is actually an array, and the function dispatch yields a promise, you can simply execute the following:

Promise.all(imageFileArray.map(file => dispatch('get_signed_request', file)))
  .then(results => console.log("completed"));

Answer №3

If you want to wait for all promises in an iterable argument to resolve, you can make use of the Promise.all method. It returns a promise that resolves only when all the individual promises have resolved successfully, or rejects with the reason of the first promise that gets rejected.

You can find more information about this in the Mozilla documentation here.

Promise
    .all(fileArray.map(file => dispatch('get_signed_request', file)))
    .then(data => console.log("All your asynchronous operations have completed"));

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

Overlapping Divs - HTML Elements Crossing Paths

My challenge is to position the Social Icons at the bottom of the screen and align the Image Gallery in the middle. However, the social Icons keep moving to the center of the screen and the Image gallery ends up overlapping them, making it difficult for me ...

Guidelines for managing UnprocessedItems with the AWS JavaScript SDK for dynamoDB

Currently, I'm facing an issue while attempting to utilize an AWS Lambda function for handling events from SendGrid. The event is expected to be in the form of an array containing a variable number of JSON objects, each representing a specific event. ...

css failing to load properly following javascript redirection

Upon clicking the button labeled id=cancel, the user will be directed to index.php. $('#cancel').click(function() { if(changes > 0){ $('#dialog-confirm').dialog('open'); }else{ window.location.href = ". ...

Tips for creating a concise summary of written content

I am interested in creating an AI-powered summary generator for text input within a textarea element. Below is the HTML code snippet I have been working with: <textarea id="summary">Enter your text here</textarea> If you hav ...

The circular reference error in Typescript occurs when a class extends a value that is either undefined, not a constructor,

Let me begin by sharing some context: I am currently employed at a company where I have taken over the codebase. To better understand the issue, I decided to replicate it in a new nestjs project, which involves 4 entities (for demonstration purposes only). ...

Encountering an issue with react-dom that needs to be resolved

After updating my node and npm installations, I encountered an error when trying to run my project. Specifically, I am using "react": "^0.13.3" and "react-dom": "0.14.0-beta3" npm WARN unmet dependency /Users/hilarl/Desktop/client/node_modules/react-do ...

What could be the reason for my React/HTML select element occasionally failing to display the default selected value?

I am currently working on creating a select element in Reactjs/HTML and I am facing an issue with setting a default value based on a component variable. Essentially, the default value of the select should be the id of a component. This is my current imple ...

Exploring the differences between an XMLHTTP request and a string and establishing a callback mechanism

After being a silent observer for quite some time, I've finally mustered up the courage to make my first post here, so please be kind... My journey with Javascript has just begun, and although I plan on delving into jQuery eventually, for now, I am f ...

We were unable to locate the requested resource

I have been working on setting up an Express endpoint to fetch comments or reviews of a movie based on the movie ID. In my initial route, I manually passed the ID and retrieved data from TheMovieDB. However, I wanted to make this process dynamic in my seco ...

What is the best way to organize data subsets in Firebase?

I am currently working on saving data from multiple sections within my webapp. One section involves storing employee information, while the other deals with employer group information. However, when I save this data in Firebase, it all gets organized by ID ...

What could be causing all the flickering in this presentation?

Check out the jQuery slideshow I uploaded on my blog at robertmarkbramprogrammer.blogspot.com/2010/09/jquery-slideshow.html The slideshow is flickering in Chrome but looks fine in IE, Firefox, and even the standalone version. You can view it here: Here i ...

The output returned by an AngularJS controller

John Papa introduced the 'controller as' technique for AngularJS in his article titled Do You Like Your Angular Controllers with or without Sugar: myApp.controller("MainCtrl", [ function () { var vm = this; // using ViewModel conv ...

Executing the stop button in the browser with Webdriver IO

Just a bit of background: The program I'm testing is located within another website that requires login credentials. Once logged in, I can access the screen I need to test by typing in the direct link. However, there's an issue where my automated ...

How can the color of the wishlist icon be modified in Reactjs when the item is available in the database?

Is there a way to change the color of the wishlist icon based on whether the item is in the database? If the item is present, its color should be brown, and if it's not present, the color should be black. Additionally, I want the ability to toggle be ...

The specified property cannot be found within the type 'JSX.IntrinsicElements'. TS2339

Out of the blue, my TypeScript is throwing an error every time I attempt to use header tags in my TSX files. The error message reads: Property 'h1' does not exist on type 'JSX.IntrinsicElements'. TS2339 It seems to accept all other ta ...

Tips for creating an editable div that can also incorporate a textarea and the option to upload or delete photos

On my website, users can upload images, names, and descriptions which are saved in a MySQL database. The information is then fetched to display on the website. The code below allows users to enter this information and see it displayed when they click the s ...

For each variable, assign a value

Apologies if this question has been asked before, but I'm encountering an issue with a foreach loop in JavaScript. let fields = temp_deviceAllocation.devices.forEach(async (device) => { const fields = await device_model .findOne({ dev ...

Obscured painting surface appearance using Three.js

I am attempting to incorporate a blurred texture into my Three.js scene, but the results are not what I expected. Canvas: var c = document.getElementById("myCanvas"); var context1 = c.getContext("2d"); context1.filter = "blur(16px)"; context1.beginPath( ...

A demonstration of VueJS Nested Builder functionality

I am currently exploring VueJS and working on a project to create a simple page builder application that allows users to add sections and subsections. I am seeking guidance on how to properly set up the Vue data property for this functionality. Any advice ...

Run the function multiple times by substituting a portion of the argument in a sequential

I am facing a challenge with a method (exampleObj.method) that requires arguments of an object and a function. The code snippet is as follows: exampleObj.method({ name1: 'string1', name2: 'string2', name3: &apos ...