0

I have a JavaScript code like this

     const toDataURL =  url => fetch(url)
            .then(response => response.blob())
            .then(blob => new Promise((resolve, reject) => {
                const reader = new FileReader()
                 reader.onloadend = () => resolve(reader.result)
                reader.onerror = reject
                reader.readAsDataURL(blob)
            }))
         toDataURL(hcmImage)
            .then(dataUrl => {
                console.log('RESULT:', dataUrl)
                hcmImageString = dataUrl.substring(dataUrl.indexOf('base64,') + 7)
                alert(dataUrl);
                alert(hcmImageString);
            })

This is implemented by another person. I want to add async to this. because sometimes code executes below code lines before executing this part.

I tried to add an async keyword like this. But it is not working


           const toDataURL = async url => fetch(url)
            .then(response => response.blob())
            .then(blob => new Promise((resolve, reject) => {
                const reader = new FileReader()
                 reader.onloadend = () => resolve(reader.result)
                reader.onerror = reject
                reader.readAsDataURL(blob)
            }))
         toDataURL(hcmImage)
            .then(dataUrl => {
                console.log('RESULT:', dataUrl)
                hcmImageString = dataUrl.substring(dataUrl.indexOf('base64,') + 7)
                alert(dataUrl);
                alert(hcmImageString);
            })

Please give me a solution to prevent executing blow code lines before this. Thank you

delma wax
  • 13
  • 2
  • Wait for the Promise to resolve... instead of *blow code lines before this*, put the code to execute either inside the `.then`, or call `.then` on the Promise (again) and put the code in that – CertainPerformance Nov 23 '22 at 03:23

0 Answers0