Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use more reliable control flow for child safeTranslator objects #35

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 26 additions & 14 deletions src/translation/translate.js
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,17 @@ Zotero.Translate.Sandbox = {
}
}

function prepareItemForParent(item) {
Object.defineProperty(
item,
"complete",
{
value: translate._sandboxZotero.Item.prototype.complete,
enumerable: false,
}
);
}

if(typeof type !== "string") {
throw(new Error("loadTranslator: type must be a string"));
return;
Expand Down Expand Up @@ -333,14 +344,7 @@ Zotero.Translate.Sandbox = {
try {
item = item.wrappedJSObject ? item.wrappedJSObject : item;
if(arg1 == "itemDone") {
Object.defineProperty(
item,
"complete",
{
value: translate._sandboxZotero.Item.prototype.complete,
enumerable: false,
}
);
prepareItemForParent(item);
}
arg2(obj, item);
} catch(e) {
Expand Down Expand Up @@ -372,19 +376,27 @@ Zotero.Translate.Sandbox = {
return translation.getTranslators();
};

var doneHandlerSet = false;
safeTranslator.translate = async function () {
translate.incrementAsyncProcesses("safeTranslator#translate()");
setDefaultHandlers(translate, translation);
if(!doneHandlerSet) {
doneHandlerSet = true;
translation.setHandler("done", function() { translate.decrementAsyncProcesses("safeTranslator#translate()") });
}
if(!errorHandlerSet) {
errorHandlerSet = true;
translation.setHandler("error", function(obj, error) { translate.complete(false, error) });
}
return translation.translate(false);
return translation.translate(false)
.then((returnValue) => {
if (Array.isArray(returnValue)) {
returnValue = returnValue.map((item) => {
item = item.wrappedJSObject ? item.wrappedJSObject : item;
if (item && typeof item.complete === 'function') {
prepareItemForParent(item);
}
return item;
});
}
return returnValue;
})
.finally(() => translate.decrementAsyncProcesses("safeTranslator#translate()"));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's use try {} finally {} with an let returnValue = await translation.translate() instead of then.

};

safeTranslator.getTranslatorObject = function (callback) {
Expand Down