ArouG Turbosudoku
ArouG Turbosudoku

Reputation: 3

Javascript - transform a "then function" to an "async function"

I am trying to change a "function f(input).then(function(output) ...) in a form like : output = await something(input) where : input = DomElement like document.getElementById("ecran") and output = dataUrl = string we can use as image.src

I'm dealing with the (tsayen)dom-to-image library (https://github.com/tsayen/dom-to-image) ... (in the browser, not with nodes.js) and I have to deal with multiple DOMelements. The aim of dom-to-image is to get an image from a DomElement.

So, I wish to could make :

dataUrl = await something(HTMLElement)

dataUrl = output = the source of the image corresponding to the DomElement

with the definition of the library, I must script something like:

domtoimage.toPng(HTMLElement1).then(function(dataUrl1){
  // {do with dataUrl1}
domtoimage.toPng(HTMLElement2).then(function(dataUrl2){ 
  // {do with dataUrl2}
domtoimage.toPng(HTMLElement3).then
  //... etc ...

domtoimage come from the librairy (Cf enter link description here

but I don't know how much HTMLElements I have to deal with ... So, I need something like dataurl = await someasyncfunction(HTMLElement) in order to be able to run script in a loop. (someasyncfunction <=> something)

I've tried :

async function dom2url(HtmlElem) {
(resolve, reject) => {
    domtoimage.toPng(this.HtmlElem).then(async function(dataUrl) {
        return await dataUrl
    })
}

and

dataUrl = await dom2url(htmlElem)

but it doesn't match

I've read so many times "async / await", "Promises" and "Arrow function" that my head is full ! Please, can anyone help me ? Don't give me some references to these functions, of course :-) Sorry for my poor english spoken !

Upvotes: -5

Views: 52

Answers (0)

Related Questions