I have a unique issue. Let's say I have this code, which runs anonymously in a code block called a "Data Element" (Adobe Launch lingo). The code is assigned the name of the data element's name so it can be referenced in the calling components which could happen 0 to 100s of times on a single page load:
return (function() {
function main(var1, var2) {
var thirdPartyResult = thirdpartyLibrary.someMethod(var1, var2);
var returnVal = false;
if (thirdPartyResult > 6) {
returnVal = true;
}
return returnVal;
}
return main(cat, subCat);// these values are passed in from external source when data element is called.
})();
The above worked fine but I noticed timing issues because when the data element is called early in the page load (after cache clear etc.), the "thirdpartyLibrary" hasn't loaded yet. So for example, the first 3 times it is called during the page loading, the data element throws and error because "thirdpartyLibrary" doesn't exist yet, therefore I can't use the output from it which is required. Regarding the code below which I know obviously doesn't work, is syntactically wrong but expresses and conceptualizes what I would really want to do, I'd only like the main function delayed until the "thirdpartyLibrary" has loaded because my functionality in "main" depends on the "thirdpartyLibrary" but since I had to make the "main" function async, it returns a promise which has nothing to do with the data I want to return and will assign "promise pending" to my return statement ==> return main('20', '4'). I know I can't do this: return await main('20', '4') which would solve my issue or wrap my return in an async function because that wouldn't be accessible. Any idea(s) on what I can possibly do?
return (function() {
async function waitForLibrary() {
return new Promise((resolve, reject) => {
const maxAttempts = 8;
const interval = 500; // milliseconds
let attempts = 0;
function checkLibrary() {
if (typeof thirdpartyLibrary !== 'undefined' && typeof thirdpartyLibrary.someMethod === 'function') {
resolve();
} else if (attempts < maxAttempts) {
attempts++;
setTimeout(checkLibrary, interval);
} else {
reject(new Error("Timeout: Third-party library not loaded."));
}
}
checkLibrary();
});
}
async function main(var1, var2) {
await waitForLibrary();
var thirdPartyResult = thirdpartyLibrary.someMethod(var1, var2);
var returnVal = false;
if (thirdPartyResult > 6) {
returnVal = true;
}
return returnVal;
}
return main(cat, subCat);// these values are passed in from external source when data element is called.
})();
Also I'm new to promises. Thanks!