Reputation: 21
I am creating functions containing strings that need interpolation:
let createPFunc = (string) => {
return () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(`${string}`);
resolve();
}, 2000);
})
}
}
let f1 = createPFunc('String 1: ${string}');
let f2 = createPFunc('String 2: `${string}`');
f1(`search 1`).then(() => f2('search 2'))
What it prints is:
String 1: ${string}
String 2: `${string}`
I want it to print:
String 1: search 1
String 2: search 2
I tried different quoting variations, but can't find a combination that works.
How can I perform interpolation twice, or delay interpolation so ${string}
is resolved when the function is called (instead of when the function is created)?
Upvotes: 2
Views: 460
Reputation: 8556
Take a look at this answer in another question to find details on how to defer the substitution of a string interpolation.
I am using the defer
function here for that.
You can achieve what you want by doing this:
function defer([first, ...rest]) {
return (...values) => rest.reduce((acc, str, i) => acc + values[i] + str, first);
}
var createPFunc = (template) => {
return (string) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(template(string));
resolve();
}, 2000);
})
}
}
var f1 = createPFunc(defer`String 1: ${'string'}`);
var f2 = createPFunc(defer`String 2: ${'string'}`);
f1(`search 1`).then(() => f2('search 2'))
// result:
// String 1: search 1
// String 2: search 2
Upvotes: 1