Please see this fiddle. I have a globalPromiseList array that controls a page loading spinner on my site. After all the promises in that array are done, remove the loading spinner. First declare global list before any JS:
var globalPromiseList = [];
Then I may have individual promises on the page for something I want done while spinner is hiding page. Here I create my individual promises and add them to the global promise list. NOTE: I must setup promise like this because I am hooking into events from third party libraries, I cannot put the code instead the containing promise block (see Resolve Javascript Promise outside function scope).
function someActionDone(id) {
window[id].resolve({
then: function (result) {
console.log(id + " loaded!");
return result;
}
});
};
[
("groups-no-dropdown"),
("groups-default"),
("groups-extended"),
].forEach(function(id) {
window[id] = { resolve: undefined, reject: undefined };
window[id + "loaded"] = new Promise(function(resolve, reject) {
window[id].resolve = resolve;
window[id].reject = reject;
});
globalPromiseList.push(window[id + "loaded"]);
});
$(document).ready(function(){
[("groups-no-dropdown"),
("groups-default"),
("groups-extended"),
].forEach(function(id) {
someActionDone(id);
});
});
Then all promise check to remove spinner:
Promise.all(globalPromiseList).then(function () {
$("#loading-overlay").css("overflow", "unset");
$("div#page.loadingoverlay").animate({
opacity: "toggle"
},
{
duration: 1200,
specialEasing: {
width: "linear"
},
done: function() {
$("div#page.loadingoverlay").toggle(false);
}
});
console.log('all promises finished');
});
However, all my promises stay in pending status, despite the console log being called in the .then
.
Please see this example: https://jsfiddle.net/DOTang/whwqp5nn/
Check console out, you see 3 loaded messages, but the promises are still pending.
I then try to call resolve().then()
instead of supplying then inside the resolve call:
window[id].resolve().then(
function (result) {
console.log(id + " loaded!");
return result;
}
);
But that gives me an error of:
Cannot read property 'then' of undefined
What am I doing wrong?
EDIT Thanks to the comments I was able to solve this like so: https://jsfiddle.net/DOTang/whwqp5nn/1/ my resolve/then usage was wrong. It should be like so, add:
window[id + "loaded"].then(function(id){
console.log(id + " loaded!");
});
Then change comboboxDataBound to:
function comboboxDataBound(id) {
window[id].resolve(id);
};