invoking a function with a callback within a loop

I need to execute

window.resolveLocalFileSystemURI(file,success,fail)
within a for loop where different file entries are passed. The goal is to only return the resolved entries in an array once all entries have been successfully retrieved.

function resolveFiles(result,callback)
{
    var resultData=[];
    window.resolveLocalFileSystemURI(result, function(entry)
    {
        resolvedGalleryImages.push(entry);

        callback(resolvedGalleryImages);
        resolvedGalleryImages=[];

    }, function(e)
    {
        alert("err"+e);}); 
}

//calling--
//@filesarr contains URIs of captured images
for(i = 0; i < filesarr.length; i++)
{
    resolveFiles(filesarr[i],function(result){
        var resultArr = result;
    });
}

What steps can I take to ensure that the callback is not triggered before all entries have been obtained?

Answer №1

When faced with a problem like this, there are several approaches you can take:

  1. Manually code an asynchronous loop
  2. Utilize promises to synchronize multiple async operations
  3. Employ a library such as Async to manage multiple async operations

Here is the manual approach:

function getFiles(filesarr, doneCallback) {
    var results = new Array(filesarr.length);
    var errors = new Array(filesarr.length);
    var errorCnt = 0;
    var overallCnt = 0;

    function checkDone() {
        if (overallCnt === filesarr.length) {
            if (errorCount) {
                doneCallback(errors, results);
            } else {
                doneCallback(null, results);
            }
        }
    }

    for (var i = 0; i < filesarr.length; i++) {
        (function(index) {
            window.resolveLocalFileSystemURI(url, function (entry) {
                results[index] = entry;
                ++overallCnt;
                checkDone();
            }, function (e) {
                errors[index] = e;
                ++errorCount;
                ++overallCnt;
                checkDone();
            });
        })(i);
    }
}

getFiles(filesarr, function(errArray, results) {
    if (errArray) {
        // handle errors here
    } else {
        // process results
    }
});

And here's an implementation using ES6 promises:

// create a promisified function
function resolveFile(url) {
    return new Promise(function(resolve, reject) {
        window.resolveLocalFileSystemURI(url, resolve, reject);
    });
}

function getFiles(filesarr) {
    var promises = [];
    for (var i = 0; i < filesarr.length; i++) {
        promises.push(resolveFile(filesarr[i]));
    }
    return Promise.all(promises);
}

getFiles(filesarr).then(function(results) {
    // process results here
}, function(err) {
    // handle error here
});

Answer №2

Assuming all your functions are synchronous, if they're not, please specify the tool you're using (note that jQuery is not used in this code snippet despite the tags).

function getFile(path) {
    var content;
    window.getFileContent(path, function(file) {
        content = file;
    });
    return content;
}
var filesContent = fileArray.map(getFile);
callbackFunction(filesContent);

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

Searching with Jquery Ajax

For my search functionality, I am utilizing ajax jquery js. I found this useful code snippet here: However, I am facing some challenges with the following Javascript code: <script language="JavaScript" type="text/javascript"> <!-- function searc ...

Using JavaScript to grab an entire div containing an SVG element

I am looking to capture an entire div as an image and save it locally as proof. Despite reading numerous articles on converting SVG to image or div to image, I have encountered challenges in achieving the desired result. Several attempts with JavaScript l ...

How can I load only specific images on a webpage using HTML?

I attempted to implement an image filter for my website by using the code below: <script> function myFunction() { // Initialize variables var input, filter, ul, li, a, i; input = document.getElementById('myInput'); filter = input.value.toU ...

Difficulties in Configuring Testacular Integration with Jasmine and Angular

I'm in the process of setting up a unit testing environment for my project and encountering some difficulties. Specifically, I am attempting to utilize Testacular with Jasmine to test my AngularJS code. One of the challenges I am facing involves a mo ...

Utilizing ES6 array methods to convert multidimensional arrays into chart-ready data

Seeking help with converting an array to a specific data format for chart display. The chrart.js library requires data in the following format: dataset = [ { label: 'one', data: []}, {label: 'two', data: []} ]; I ...

Searching in Vue based on the selected option is only possible by the selected criteria and not by id, regardless of the

#1 Even if chosen, cannot search by id. The 'name' condition in the loop works well but I am unable to correctly search by id (returns nothing). #2 When selecting an option from the dropdown menu, it only displays until I start typing. I would l ...

The direction to the Excel document for conversion into JSON

I have a project in progress where I'm currently working on converting an Excel sheet to JSON. Once the data is converted, it will be displayed using jQuery Datatables on the browser. My code is functioning as expected, but I am encountering an issue ...

One Background Image Serving Multiple Divs

Can you use one image (PNG or SVG) as the background for multiple divs? Take a look at the images below to see how it could work. And if the screen width gets smaller and the divs stack up vertically, is there a way to change the background accordingly? D ...

When attempting to navigate to a different page in Next.js, the Cypress visit functionality may not function as

In my upcoming application, there are two main pages: Login and Cars. On the Cars page, users can click on a specific car to view more details about it. The URL format is as follows: /cars for the general cars page and /cars/car-id for the individual car p ...

What is the best way to keep calling an AJAX function until it receives a response from a previous AJAX call

I am looking to continuously call my ajax function until the previous ajax call receives a response. Currently, the page is loading every second and triggering the ajax function, but I want it to keep calling the ajax function until the previous one has c ...

Running multiple web applications with different base directories on a single Express server

I am currently working on serving a website that requires different static directories for various routes. When a GET request is sent to the /tools* route, I want to utilize the /dist/toolsApp/ directory as the base directory for my frontend code. If ...

Issue with AngularJS ui-router failing to resolve a service call

I am facing an issue while trying to implement the resolve feature in my ui-router state provider. Here is how I have configured it: app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function ($stat ...

Customize Input Values by Selecting an Option with jQuery-UI Autocomplete

Hello there, I am a newcomer to java-script and could really use some help. My goal is to have the data in the country field automatically populated when a user enters data into the city field. I have an xml file: <ROWSET> <ROW> <city>&l ...

Using location.reload with the argument of true is no longer recommended

While it's generally not recommended to reload an Angular Single Page Application, there are situations where a full reload is necessary. I've been informed by TSLint that reloading is deprecated. Is there any other solution available for this ...

Unlocking Extended Functionality in JQuery Plugins

At the moment, I am utilizing a JQuery Plugin known as Raty, among others. This particular plugin typically operates as follows: (function($){ $.fn.raty = function(settings, url){ // Default operations // Functions ...

Adding extra information to a property or array in Firebase

The following code snippet demonstrates how to create an array of event objects using observables. eventsRef: AngularFireList<any>; events: Observable<any>; this.eventsRef = db.list('events'); this.events = this.eventsRef.snapshotC ...

Learn how to create a "generated" texture coordinate in three.js similar to how it is done in Blender Cycles

How can I properly display a texture on a cylinder object using THREE.js without distortion? Currently, the texture appears stretched along the edges of the cylinder as shown here: https://i.sstatic.net/O2YFr.png This issue is based on the texture provide ...

Strategies for handling numerous node projects efficiently?

Currently, we are utilizing three distinct node projects: Project 1, Project 2, and Project 3 incorporating react and webpack. Each of these projects is stored in their individual repositories. While Project 1 and Project 2 operate independently, Project ...

Rails not receiving JSON data

I am attempting a straightforward ajax call in Rails 4, but encountering issues with retrieving the json response. Below is the script I'm working with: $(document).on "submit", "form[name=upvote-form]", -> form = $(this) $.post "/vote", $(th ...

A script in PHP or JavaScript that dynamically generates two dual drop-down menus to assist with data selection

I have experience with php scripting, but I am facing challenges when trying to combine it with JavaScript. The issue arises when I have a form that includes dropdown menus for categories and subcategories. When a category is selected, the options in the s ...