I wrote the following code to resize an image:
Main().then(function(x) {
console.log(x)
});
Main=function() {
Base64()
.then(function(i) {
ImageObject(i)
})
.then(function(i) {
x = Resize(i);
NOW RETURN 'x'
AS A PROMISE
}) //***
});
}
function Base64(i) { //Generate base64 of the image
let reader = new FileReader();
reader.readAsDataURL(imaginary.file());
return new Promise((resolve, reject) => {
reader.onload = () => {
resolve(reader.result)
}
});
}
function ImageObject(i) { //Load the image
let img = new Image(0, 0);
img.src = i;
return new Promise((resolve, reject) => {
img.onload = () => {
resolve(img)
}
});
}
function Resize(i) { //Resize image and return base64
let canvas = document.createElement('canvas');
let canvasContext = canvas.getContext('2d');
canvas.width = 300;
canvas.height = 200;
canvasContext.drawImage(i, 0, 0, canvas.width, canvas.height);
return canvas.toDataURL(); //Return the resized base64
}
In the line with the ***, I need to return x as a promise to allow Main to be 'thenable'.
xas a promise"?! You can create a promise of (i.e. resolving tox) withPromise.resolve(x), but why would you? You already have a promise chain, whatever you return from the then callback is what it'll resolve to.asyncandawait(is there any reason you can't?), as that will help with the problem you're having of nesting vs. chaining callbacks. Can you successfully haveMaincall one asynchronous operation and successfully return aPromise? Once that works then move on to calling a second asynchronous operation, and so on.awaitsyntax then a single asynchronous operation inMainmight look like:const Main = async () => { await Base64(); };Withoutawaitsyntax it might be:const Main = () => Base64();or:const Main = () => { return Base64(); };Or if you can't use arrow functions for some reason?:function Main() { return Base64(); }There are a variety of ways to structure it, and any way will involveMaineither awaiting or returning thePromiseof any function it calls.