0

I have used the below code to add multiple attachments to a list item

function AddAttachments(itemID) {
    //Retrieving all the files which are available in an Array, Created  this Array in 
    //the above step(Step 2)
    for (var i = 0; i < fileCount; i++) {
    if (fileData[i] != '')
         $().SPServices({
             operation: 'AddAttachment',
             async: false,
             listName: 'Documents',
             listItemID: itemID,
             fileName: fileName[i],
             attachment: fileData[i],
             completefunc: function (xData, Status) {
             }
         });
   }
}

The code works really well but sometimes when there are lets say 10 attachments that need to be attached, 9 of the files get attached successfully and one file would fail to get attached because of a network error. The error occurs very randomly and it is unpredictable.

XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3.

The error would occur silently and the user would not even be aware that one of the files did not get attached. I saw the error because I was watching the network tab in Developer Tools in IE

What I would like is - to modify the above code to -if a network error occurs while trying to attach then to retry the operation again and go on retrying until it succeeds. Because of the random nature of this error I am very confident that if the attachment operation is retried immediately after a failure due to network error, it would succeed in the following attempt.

Can someone help with any tips on how to go about the above? Any assistance will be much appreciated. Thanks...

0

Do not use a for loop, use the avaible callback pattern

  • pop/unshift the array of attachments.

  • Do ONE upload
    (async:true recommended not required, helps performance if you have other async code going on)

  • use the completefunc to proces the next attachment (in the array)
    (call the ONE fileupload again)

  • 1
    why do you think a For loop should not be used? – vivek m Dec 1 '17 at 16:59
  • A for loop iterates, that's all it does. You can't redo an iteration.. which is what you, on failure, want to do. That's why the Callback (function) pattern was developed ages ago. We now use Promises, or Async/Await in the latest Javascript – Danny '365CSI' Engelman Dec 4 '17 at 7:03
  • thanks for the explanation Danny. that was very helpful. Thanks again, have a nice day – vivek m Dec 4 '17 at 17:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.