0

I have a classic synchronicity problem (cue the Police), and I'm sure there's an easy way to fix it, but I can't figure it out. I need to modify an XML string in the middle of a Javascript function. The best way to do it is to use AJAX to call the server and use a back-end Java method to do the modification. The problem, of course, is that the rest of the Javascript function just keeps executing, even though it has not received the modified string back from the AJAX method. I understand that I'm supposed to use a Promise object for this kind of problem, but I've never used Promise objects before, and I can't seem to get it to work here. Here are the relevant snippets of code. Advice is most welcome.

var molstruct = ...;
rxnIds = getRxnIds();
modifyMrvWithRxnConditions(molstruct, rxnIds, '../').then(
  function (modifiedMrv) {
    molstruct = modifiedMrv;
  }
);

var modifyMrvWithRxnConditions = function (mrv, rxnIdsStr, pathToRoot) {
  "use strict";
  return new Promise(function (resolve, reject) {
    var modifiedMrv =
      modifyMrvProperty(mrv, 'reactionIds', rxnIdsStr, pathToRoot);
    resolve(modifiedMrv); // shouldn't it wait for the result from modifyMrvProperty ?
  });
} // modifyMrvWithRxnConditions()

// Uses AJAX to call a JChem method that modifies the MRV.
function modifyMrvProperty(mrv, propertyName, propertyValue, pathToRoot) {
  "use strict";
  var toSend = new String.builder().
  append('mrv=').
  append(encodeURIComponent(mrv)).
  append('&propertyName=').
  append(propertyName);
  if (!isEmpty(propertyValue)) {
    toSend.append('&propertyValue=').
    append(encodeURIComponent(propertyValue));
  } // if there is a value
  callAJAX(pathToRoot + 'includes/modifyProperty.jsp',
    toSend.toString(), finishModifyProperty);
} // modifyMrvProperty()

// Gets the MRV with the molecule property inserted.
function finishModifyProperty() {
  "use strict";
  if (xmlHttp.readyState === 4) {
    var responsePage = xmlHttp.responseText;
    var mrvValue = extractField(responsePage, 'mrvValue');
    return mrvValue;
  }
} // finishModifyProperty()
Phil
  • 157,677
  • 23
  • 242
  • 245

0 Answers0