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?

1
  • 2
    Does const data = await Promise.all(this.retrieveData()) do what you mean? Commented May 22, 2018 at 4:38

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Just curious, what if retrieveData() was returning Promise<string[]> instead? Do I still use Promise.all?
No, this would be await this.retrieveData(), as you originally suggested.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.