soubhagya pradhan
soubhagya pradhan

Reputation: 547

javascript function logging before finishing work

import html2canvas from 'html2canvas';

export default async function htmlToImg(id) {
  applyShadow(false);
  return await html2canvas(document.getElementById(id), {
      scale: 1
    })
    .then(canvas => {
      applyShadow(true);
      let img = canvas.toDataURL('image/png')
      console.log(img)
      return img
    });
}

Here i shared my code.

I am trying to convert some html nodes to canvas then converting it to image url. But, it is working but, it is giving different part of complete image sometimes 50% and sometimes 70% of the image. The html is long so, i think it is printing before it is done converting html nodes to canvas or canvas.toDataURL('image/png').

The function is async function so it is logging before it is done converting complete html. Is there any way to solve it ?

Please have a look

Upvotes: 1

Views: 244

Answers (2)

Prakash Karena
Prakash Karena

Reputation: 2605

Promise : htmlToImg

export default = (id) =>  new Promise((resolve, reject) => {
        html2canvas(document.getElementById(id), {
            scale: 1
        }).then(canvas => {
            let img = canvas.toDataURL('image/png')
            resolve(img,null)
        }).catch(err=>reject(null,err);
})

Use of your promise

import htmlToImg from 'your htmlToImg path';

htmlToImg(pass_your_id)
.then( ( image , err ) => { 
 if(err) { console.log(err) } 
 console.log('my image',image)
})

Upvotes: 1

Vipulw
Vipulw

Reputation: 1283

To use await, the operation on which you are awaiting should be a promise returning function. So, even though you have put await, code is still working asynchronously. You need to return promise in await as below :

async function htmlToImg(id) {
    applyShadow(false);
    myImg = await new Promise((resolve, reject) => {
        html2canvas(document.getElementById(id), {
            scale: 1
        }).then(canvas => {
            applyShadow(true);
            let img = canvas.toDataURL('image/png')
            console.log(img)
            resolve(img)
        });
    })
    return myImg
}

I hope this resolves your issue. Please let me know if you still facing any issue, I will see if I can help you more.

Upvotes: 6

Related Questions