1

I've written a function using pnp-js-core to batch checkout, update and checkin selected items.

Problem I'm seeing however is that it seems that by the time the first map is called the next one proceeds but the result from the return hasn't finished so there isn't anything in the fileRefs=[]?

// Update files
function exclude(isTrue) {
  // Get selected files from list
  var selectedItems = SP.ListOperation.Selection.getSelectedItems().map(x => x.id)
  var myFieldValue = isTrue ? "true" : "false";
  var batch = $pnp.sp.createBatch(); // Create batch object
  var fileRefs = []; // Store selected files reference
  var documentLibrary = $pnp.sp.web.lists.getByTitle("Documents"); // Get document library


  // Get fileRef from selected items
  selectedItems.map(function(item) {
    documentLibrary
      .items
      .getById(item)
      .select("FileRef")
      .inBatch(batch)
      .get()
      .then(x => fileRefs.push(x.FileRef))
  })

  // Check out selected files
  fileRefs.map(function(fileRef) {
    $pnp.sp.web.getFileByServerRelativeUrl(fileRef)
    .inBatch(batch)
    .checkout()
      .then(() => {
          console.log("File checked out:", fileRef);
      });
  })

  // Update file property
  selectedItems.map(function(itemID) {
    documentLibrary
      .items
      .getById(itemID)
      .inBatch(batch)
      .update({
        ccaGrantExcludeFromPAC: myFieldValue
      })
  })

  // Check in file
  fileRefs.map(function(fileRef) {
    $pnp.sp.web.getFileByServerRelativeUrl(fileRef)
    .inBatch(batch)
      .checkin()
        .then(() => {
          console.log("File checked in!");
        });
  })

  // Execute batch?
  batch.execute().then(
    () => console.log("Files have been updated successfully") );
}
0

You can manage asynchronous call of jquery using deferred. It manage the asynchronous call to execute in synchronous way.

function wait(ms) {
      var deferred = $.Deferred();
      setTimeout(deferred.resolve, ms);

     // We just need to return the promise not the whole deferred.
     return deferred.promise();
  }

  // Use it
  wait(1500).then(function () {
      // Call you another function
      wait(1000).then(function () {
           // Do something or call your function
      });
  });

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.