javascriptpromisethenable

JavaScript return last then as a promise


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'.


Solution

  • then() always returns Promise. you should just add return from your Main and inside last then()

    Main().then(function(x) {
      console.log(x)
    });
    // If you call it before definition, it must be var, or just a normal function
    //    Main = function() {
    // var Main=function() {
    function Main(){
      return Base64()
        .then(function(i) { return ImageObject(i) })
        .then(function(i) { return Resize(i) })
    
    }
    
    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
    }