简体   繁体   中英

How to use promises correctly?

  1. I have a sharepoint form where the user fill some textboxes.

  2. The user click on the save button. The script run from here.

  3. Check if all texbox is filled or not.

  4. If good, get some fields from an outer list based on the inputs and update some other list based on that.

  5. Save the inputs as a new item.

The problem: I use a function named PreSaveAction() . This called when the user click on the "Save" button and only if this return with true the form ll be saved. So before returning with true I should do the field check and list updates, I don't know where to add this return true . If I add this directly inside the PreSaveAction() it's running asyncron so with 30-40% chance returns before the update is done. I am new to javascript so I need a little help.

My simplified code looks like this:

function PreSaveAction() //This start if the user click on the save button, and create a new item if return with true
{
  var promresult;
  if(textbox!="")
  {
    //do my staff based on promise like: promresult=promise.then(input textbox, get list field).then(update).then(resolve true, fail false)
    return promresult;  //this run before the update is completed and promresult get value
  }
  else
  {
    return false;  //nothing happens if the textboxes are not filled yet.
  }

}

I read about promises and I think I understanded how they work, but at my case the PreSaveAction() have multiple functions (detect onclick, do my stuffs, return with true/false). I tryed several approach, but I coudn't find the solution where and how to place the return from presave to wait my promise to finish? Or should I use completly different approach? Thanks you very much for your kind help!

function PreSaveAction() //This start if the user click on the save button, and create a new item if return with true
{
  var promresult;
  if(textbox!="")
  {
    //do my staff based on promise like: promresult=promise.then(input textbox, get list field).then(update).then(resolve true, fail false)
    return promresult;  //this run before the update is completed and promresult get value
  }
  else
  {
    return Promise.resolve(false);  //nothing happens if the textboxes are not filled yet.
  }

}

PreSaveAction()
  .then(function(result){
    if (result===false) {
      // this means the textboxes are not filled yet
    } else {
      // result is whatever is returned from promresult
    }
  })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM