I'm trying to load a bunch of resources async using promises with Jimp.js
. The loading code is a disaster trying to chain it all, and I need a cleaner solution.
What I came up with was below. This obviously doesn't do anything, because it's junk code, but I need to know if there was a failure loading any of the resources, and I need to know when they completed.
function doSomething(asdf) {
return new Promise((resolve, reject) => {
//console.log("It is done.");
// Succeed half of the time.
var x = Math.random();
if (x > .5) {
resolve(["SUCCESS",asdf,x])
} else {
reject(["Failure",asdf,x])
}
});
}
func();
function func() {
//Imagine a is actually an image loaded by doSomething
var a=null; doSomething("1").then(function (data) {a = data;},
(err) => {throw new err;});
//Imagine b is a font resource.
var b=null; doSomething("2").then(function (data) {b = data;},
(err) => {throw new err;});
Promise.all([a, b]).then(function() {
console.log(a);
console.log(b);
//Then here I expect everything to be correct, and continue on with the next function.
},
(err) => {console.log('Oops:' + err);}).
catch( (err) => {console.log('Oops:' + err);});
}
For some reason, this never outputs "Oops".
Here is a fail output:
[ 'SUCCESS', '1', 0.756461151774289 ] null
What am I missing here?
Update
I took part of an answer I received and changed it so that it behaves exactly as I wanted:
function func() {
var a=doSomething("1").then(function (data) {a = data;});
var b=doSomething("2").then(function (data) {b = data;});
Promise.all([a, b]).then(function() {
console.log(a);
console.log(b);
},
(err) => {console.log('Reject:' + err);});
}
Update
Here is the actual code I'm using that's working great now:
LoadResources() {
var ps = [];
console.log("Loading now");
ps.push(jimp.read(this.ipath+"c4box.png").then(function (image) {obj.imBox = image;}));
ps.push(jimp.read(this.ipath+"red.png").then(function (image) {obj.imRed = image;}));
ps.push(jimp.read(this.ipath+"green.png").then(function (image) {obj.imGreen = image;}));
ps.push(jimp.read(this.ipath+"top.png").then(function (image) {obj.imTop = image;}));
ps.push(jimp.read(this.ipath+"bot.png").then(function (image) {obj.imBot = image;}));
ps.push(jimp.loadFont(jimp.FONT_SANS_32_WHITE).then(function (font) {obj.imFont = font;}));
Promise.all(ps).then( () => {
obj.loaded = true;
obj.imBg = new jimp(512, 576, function (err, image) { });
console.log("Actually loaded now.");
obj.StartGame();
});
console.log("Loading commands complete");
}