我有一个经典的同步性问题(提示警察),我确信有一个简单的方法来解决它,但我无法弄明白。我需要在Javascript函数中修改XML字符串。最好的方法是使用AJAX调用服务器并使用后端Java方法进行修改。当然,问题是Javascript函数的其余部分只是继续执行,即使它没有从AJAX方法接收到修改后的字符串。我知道我应该使用Promise对象来解决这类问题,但我之前从未使用过Promise对象,而且我似乎无法在这里工作。以下是相关的代码片段。建议是最受欢迎的。
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()