1

In a class method, I retrieved some data through an async function, this.retrieveData(). This method returns me the data which I intend to pass it to another function called renderTemplate().

async getTemplateHtml() {
   const data = await this.retrieveData()
   const html = renderTemplate(`some html template`, {stuff: data}
   return html
}

The problem, however, is that this.retrieveData() actually returns an array of Promises in the form of Promise<string>[] while the signature of renderTemplate() is renderTemplate(string, {stuff: string[]}

I cannot pass data returned from this.retrieveData() directly into the renderTemplate()'s second parameter because the elements in data are still wrapped in a Promise. I can't change the second parameter of renderTemplate() function too because it is from a npm library.

How can I somehow resolve the values wrapped in Promises in data so that I can pass it into renderTemplate() as its actual value unwrapped from its Promise?

Carven
  • 14,988
  • 29
  • 118
  • 161

1 Answers1

3

If retrieveData returns an array of promises, it should be:

const data = await Promise.all(this.retrieveData());

This maps an array of promises to an array of values.

Estus Flask
  • 206,104
  • 70
  • 425
  • 565