Keep a collection of completed promises stored in the inventory

Good day,

I'm facing a challenge in Parse Javascript where I am trying to save items after receiving them in a loop. However, outside the loop, the array of objects remains empty.

.. define global ** var filesUpload = []**

 for (var key in files) {
         var photoUpload = new Parse.File(String(file.name),[file.image])
             photoUpload.save().then(function(item) {
                    deferred.resolve(item)

                    filesUpload.push(deferred.promise)


             }, function(error) {
                console.log("error to save file"+JSON.stringify(error))
                // The file either could not be read, or could not be saved to Parse.
            })
         }

--> end of loop

filesUpload array still has no items

Answer №1

If you want to retrieve values from multiple promises, you will need to utilize the Promise.all method. While Parse.com does not have a direct implementation of Promise.all, they offer a similar alternative:

Parse.Promise.when(files.map(function(file){
    return new Parse.File(String(file.name),[file.image]).save();
})).then(function(){
    var results = Array.prototype.slice.call(arguments);
    //results === your filesUpload
}).then(null, function(err){
    console.log("error to save file" + JSON.stringify(error));
});

If you prefer using Promise.all:

Promise.all(files.map(function(file){
    return new Parse.File(String(file.name),[file.image]).save();
})).then(function(results){
    //results === your filesUpload
}).catch(function(err){
    console.log("error to save file" + JSON.stringify(error));
});

In addition, I included the Promise.prototype.catch which may not be available in the Parse.Promise implementation. However, most promises do support this method. For instance, ES6 Promises offer both Promise.all and Promise.prototype.catch methods.

Answer №2

Asynchronous promises add an extra layer of complexity to your code. When dealing with promises, keep in mind that any code following your for loop will execute before the promise is resolved and the then function is called.

It's like trying to do this:

window.setTimeout(function() {
  document.write('inside setTimeout');
}, 1000);

document.write('after call to setTimeout');

Make sure to handle any operations involving filesUpload within the then callback of your photoUpload.save() promise. It's a good practice to extract a function and call it from there for better organization.

 for (var key in files) {
   var photoUpload = new Parse.File(String(file.name), [file.image]);
   photoUpload.save().then(function(item) {
     deferred.resolve(item);

     filesUpload.push(deferred.promise);
     goAhead();

   }, function(error) {
     console.log("error to save file" + JSON.stringify(error));
       // The file either could not be read, or could not be saved to Parse.
   });
 }

 function goAhead() {
   // go ahead
 }

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

Utilizing Vue to Embed Multiple Hubspot Forms on one Page

While working on a Vue page, I encountered an issue with loading multiple Hubspot forms simultaneously. Only one form would load at a time. Here is the code snippet I used to append a single Hubspot form: mounted() { const script = document.createElem ...

Creating an Interactive Menu System with Nested Options in Angular 2

I have a JSON structure that I need to transform into a menu with sub-menus based on the value of the sub-menu_location field. Here's an example: { "data": [ { "menu_name": "Primary Operations", "enabled": true, "sub-menu_lo ...

Random sequencing of the commands

Whenever I call the Details function, it returns empty details because the function executes before retrieving data from the json file. What is the best way to fix this issue? app.controller('loginCtrl',function($scope,login){ $scope.user=login ...

Defaulting summernote to display in italics

Looking for a way to italicize a series of summernote inputs by default? I have removed all toolbar options except the italics button. Here's the HTML generating these inputs: <div style="width:250px;"> < ...

Leveraging Vue 3 Composition API with accessors

I'm currently in the process of refactoring some of my components using the composition API. One component is giving me trouble, specifically with asynchronous state when trying to retrieve data from one of its getters. Initially, the component was u ...

What is the best way to handle responses in axios when dealing with APIs that stream data using Server-Sent Events (S

Environment: web browser, javascript. I am looking to utilize the post method to interact with a Server-Send Events (SSE) API such as: curl https://api.openai.com/v1/completions \ -H "Content-Type: application/json" \ -H ...

Having trouble running Ajax with JavaScript on a Wamp server

Exploring the realm of ajax, I embarked on a journey guided by a YouTube tutorial to construct a basic food search application. The concept was simple - users would input the name of a food item, and if available, its name would be displayed below. On the ...

What could be causing my browser to not respond to the JavaScript function for clicking?

I have been struggling to get the images on my browser to change when I click on them. Despite my efforts, I haven't found a solution yet... I've experimented with changing the variables to ".jpg" and also tried removing them altogether. var ...

Favicon not appearing on Jekyll website

This is my first time working with Jekyll. I'm currently working on localhost and trying to set a favicon for the website. I generated the image.ico and added the code provided to my head.html file. The image appears in my _site folder, but it's ...

Enhancements to managing universal configuration object across the entire application

My current project involves working on an application with multiple products. To streamline product-specific configuration and eliminate the need for excessive if-else statements, I am looking to implement product-specific config keys that are consistently ...

Issue with Angular 7 Universal: components inside are failing to display

I have successfully implemented Angular 7 Universal with dynamic server-side rendering. However, I am facing an issue where dynamic components within the main component being rendered on the server are not rendered themselves. Here is an example of the re ...

Executing a Javascript function from a C# WebBrowser: A Step-by-Step Guide

I am currently working on web automation using C# and a WebBrowser. There is a link that I need to 'click', however, since it triggers a Javascript function, it seems that the code needs to be executed rather than simply clicking the element (i.e ...

Attempting to establish both the minimum and maximum time date in a jQuery datepicker across two separate inputs

I've been working on a project for my classes that requires setting minimum and maximum dates for two input fields. The first input should allow dates from now to 12 months in the future, while the second input should be restricted to dates picked wit ...

Restrict User File Uploads in PHP

I have a system set up that enables users to upload files under 200 MB. Once the file is downloaded once, it will be automatically deleted. Additionally, all files are deleted from the server after 24 hours. I am looking for a way to limit the number of up ...

Pressing the Add button will create a brand new Textarea

Is it possible for the "Add" button to create a new textarea in the form? I've been searching all day but haven't found any logic to make the "Add" function that generates a new textarea. h1,h2,h3,h4,h5,p,table {font-family: Calibri;} .content ...

Is there a way to distribute my World instance among several step definition files in CucumberJS?

Currently, I am working on implementing a CucumberJS scenario that involves using multiple steps spread out across two separate step definition files. In this setup, the first step establishes certain variables in the World object which need to be accessed ...

Is there a way to automatically update the state in ReactJS whenever new information is added or deleted, without the need to manually refresh the page

I have encountered an issue that I have been trying to resolve on my own without success. It seems that the problem lies in not updating the Lists New state after pushing or deleting from the API. How can I rectify this so that manual page refreshing is no ...

Automatically include the date as a column heading along with name and ID

I recently came across a guide on how to dynamically add dates as column headers in a table. However, I encountered an issue where I couldn't add new columns for 'Name', 'Age', and 'Section' before the dynamically generat ...

Analyzing elements within an array of objects

Here is an array of objects I have: const cart = [ { group: "group 1", qtd: 12, value: 65, term: 20 }, //index 0 { group: "group 1", qtd: 10, value: 100, term: 20 }, //index 1 { group: "group 1", qtd: 18, value: 40, term ...

Prevent $.ajax with jQuery when a button is clicked

Is there a way to interrupt the $.ajax() function execution by clicking on this button: <button class="stop">Stop</button> Is there a specific function that can cause the $.ajax() call to stop? Note: The $.ajax script is within a function, l ...