TransWikia.com

call executeQueryAsync mutliple times and add results into an array

SharePoint Asked by I-junior on February 26, 2021

I am trying to get the Files Urls from selected documents. I am using SPContext to make a call and then using a callback function to push results into an array then later in the code I loop through the array to access the urls so I can download the documents. However, the problem is that it downloads documents double times or triple times, depending on how many I have selected.

My questions are:

  1. how can I retrieve the urls of the selected documents. Is there a better way than the one I have so far?
  2. How can I download only a single copy of the document, thus avoiding double download of the same document?
  3. For my understanding, how can I call executeQueryAsync multiple times and store the response in an array as I have done below? Please let me know how can I improve my code.

I am using Sharepoint 2013. Thank you for your help.


function DownloadFiles(onComplete) {
        var selectedItems = SP.ListOperation.Selection.getSelectedItems(ctx);
        var count = selectedItems.length;
        if (count == 0) {
            alert("Please select an item from the list");
            return false;
        }
        var arrOfLinks = [];
        for (i in selectedItems) {
            var clientContext = new SP.ClientContext();
            var targetList = clientContext.get_web().get_lists().getByTitle(ctx.ListTitle);
            targetListItem = targetList.getItemById(selectedItems[i].id, 'FileLeafRef', 'ContentType', 'File', 'FileRef');

    
            clientContext.load(targetListItem);
            arrOfLinks.push(targetListItem);
            clientContext.executeQueryAsync(() => {
                onComplete(arrOfLinks);
            }, Function.createDelegate(this, this.onQueryFailed));
        }
    }
    
    function myCall() {
        DownloadFiles((arrayOfLinks) => {
          for (var i = 0; i < arrayOfLinks.length; i++) {
             var url = window.location.origin + arrayOfLinks[i].get_item('FileRef');
            window.location.href = `/_layouts/15/download.aspx?SourceUrl=${url}`;
           }
        });
    }
    
    function onQueryFailed(sender, args) {
        alert('Request failed. nError: ' + args.get_message() + 'nStackTrace: ' + args.get_stackTrace());
    }

One Answer

Have a look at this other post. I think it will answer your question:

Using getSelectedItems to get a field value instead of ID

Correct answer by Imir Hoxha on February 26, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP