I'm developing my first library in javascript.
Sorry if I don't explain myself well because my english level is not good and probably I'll do grammatical errors, so apologies.
My problem is that when I call initService function that I've created in my library return a promise, but I want that return the real value of service property. I've write logs inside that method and this is how show all logs.
[library] calling...
[html file] html calling... -> return a Promise
[library] finished -> return value of service.
I knwo that in moment when I call initService from my html file is a Promise and later when promise has finished return the value.
How can do that when I call initService on my html file return the value of service and not a promise?
Here is my code in html file:
<html lang="en">
<head>
<script src="./js/library.js"></script>
</head>
<body>
<script type="text/javascript">
let service = window.APIServiceLibrary.initService('APIService');
console.log('html calling... ', service);
</script>
</body>
</html>
Here is my library:
(function(window) {
// You can enable the strict mode commenting the following line
// 'use strict';
function APIServiceLibrary(){
var _serviceLibraryObject = {};
var props = {
service: undefined,
intervalID: undefined
};
_serviceLibraryObject.createService = function(name) {
return new Promise(resolve => {
setInterval(() => {
props.service = this.getAPIService(name);
if (props.service !== undefined) {
this.stopService(props.intervalID);
resolve(props.service);
}
}, 500);
});
};
_serviceLibraryObject.getAPIService = function(name) {
// window.APIService is a global value
if (window[name] !== undefined) {
return window[name];
}
};
_serviceLibraryObject.stopService = function() {
for (var i = 1; i < props.intervalID; i++) {
window.clearInterval(i);
}
}
_serviceLibraryObject.initService = async function(name){
console.log('calling...');
props.service = await this.createService(name);
console.log('finished: ', props.service);
return props.service;
};
return _serviceLibraryObject;
}
if(typeof(window.APIServiceLibrary) === 'undefined'){
window.APIServiceLibrary = APIServiceLibrary();
}
})(window);
EDITION:
html file:
<script type="text/javascript">
window.APIServiceLibrary.createService('APIService')
.then(service => {
// call functions that you need
console.log('service: ', service);
})
.catch(err => {
console.log('error: ', err);
});
</script>
Remove from the library next method:
_serviceLibraryObject.initService = async function(name){
console.log('calling...');
props.service = await this.createService(name);
console.log('finished: ', props.service);
};