0

I have a case where a template literal can resolve a variable immediately, but the next in order doesn't. I have to wait for a response. It looks like this:

const firstValue = 'firstItemName'
const myTemplate = `
    First item: ${firstValue} is available! But not the second: ${secondValue}
`;
const secondValue = 'secondItemName';

This secondValue will come, in my case, from a Promise call. Is there no way to use the string literal as a reference instead as final value?

Daniel M
  • 61
  • 1
  • 8
  • can you precise the use case ? why do you want to do that ? – Basile Beldame Jan 19 '20 at 22:03
  • 1
    why don't you declare a function that return the string you want every time you want passing firstValue and secondValue – Ali Faris Jan 19 '20 at 22:05
  • @BasileBeldame Because I don't want to use React or any overkill library for a simple use case where I'm building a very, very small portion of my markup. The use case is...well, the general use-case of programming: build strings. – Daniel M Jan 19 '20 at 22:05
  • 1
    Just move the template string down after the code that awaited the promise. Or put it inside a function if you want to keep it at the top. – Bergi Jan 19 '20 at 22:07
  • 1
    You're not going to be able to do this without wrapping it in a function. When this is evaluated, `myTemplate` is a string and strings are immutable. You need to create the string once you have the values or wrap the string creation in a function. – Mark Jan 19 '20 at 22:08

0 Answers0