I'm using a series of promises to maintain the correct order of operations so that I can load some data, and initialise some objects before my app/page loads.
In the process of making my code more modular so I can reuse some of the functions, I've seemingly overstepped my understanding of promises and I'm finding that the .then chain after initApp() is not executing ever - the promise is simply resolved/rejected instantly.
My getData function works perfectly:
function getData(promises, callback) {
let getDataComplete = new Promise(function (resolve, reject) {
Promise.all(promises)
.then(function () {
if (callback && typeof callback === "function") {
debug_log("getData: running callback");
callback();
}
return resolve;
})
.catch(function (error) {
return reject;
});
});
return getDataComplete;
}
But the section below (which executes it) doesn't wait for it to finish?
const initApp = new Promise((resolve, reject) => {
let dataReturned = getData([
getPartners,
getProducts,
getCurrencies,
getSites
]);
if (dataReturned == resolve) {
debug_log("resolve initapp")
resolve;
} else {
debug_log("reject initapp")
reject;
}
});
initApp
.then(() => {
initJSComponents();
})
.catch((error) => {
debug_log("Problem during js component initialisation.", error);
})
.then(() => {
initDOM();
})
.then(function () {
//some more stuff here
})
.catch((error) => {
debug_log("Problem during initialisation.", error);
});
Any ideas? I'm stumped and I've been looking at and rewriting it over and over for hours.
You have your getData function returning Promise, but you didn't used Promise#then or Promise#catch methods after execution. So after the calling this function you getting Promise object immediately without waiting. You should probably change your initApp function like that:
const initApp = new Promise((resolve, reject) => {
getData([
getPartners,
getProducts,
getCurrencies,
getSites
]).then(() => {
debug_log("resolve initapp")
resolve();
}).catch(() => {
debug_log("reject initapp")
reject();
});
});
Only after that your initApp will resolve (or reject) his Promise after the Promise returned by getData function will get resolved (or rejected).
function getData(promises, callback) {
return new Promise(function (resolve, reject) {
Promise.all(promises)
.then(function () {
if (callback && typeof callback === "function") {
debug_log("getData: running callback");
callback();
}
resolve();
})
.catch(function (error) {
reject();
});
});
}
const initApp = new Promise((resolve, reject) => {
getData([
getPartners,
getProducts,
getCurrencies,
getSites
]).then(allFine => {
resolve();
}, somethingWrong => {
reject();
});
});
initApp
.then(() => {
initJSComponents();
})
.catch((error) => {
debug_log("Problem during js component initialisation.", error);
})
.then(() => {
initDOM();
})
.then(function () {
//some more stuff here
})
.catch((error) => {
debug_log("Problem during initialisation.", error);
});