\
TL;DR (Too Long Didn't Read) Function const render = async (x, ...values) => { var rendered = ""; for (let u = 0; u < x.length; u++) { rendered = rendered.concat(x[u]); if (u < x.length - 1) { if (typeof values[u] == "function") { var res = await values[u]() if(res) rendered += res; } else { rendered +=values[u] } } } return rendered; }; Usage const result = render`My string is = ${()=> {return (1 + 1)}}` console.log(result) // output -> My string is 2 What Is This?By render, I meant being able to run async and sync functions inside of a string. Which may be called templating.
\ This is a basic function which uses template literals, it can run the functions inside of a string which lets us to do many things like, retrieve data from database, fetch data from an API, calculate stuff which is provided earlier and so on.
How it worksYou may understand what it does from the code above if you have prerequisite knowledge about tagged templates, it just runs the functions and put the output of function in the place where function executed.
WarningIn many times using async functions inside async functions inside async functions are required and without using proper async await functionality, this stuff is getting too error prone. It may return [Object Promise][Object Promise][Object Promise]. With a simple Promise.all(), we can fix all of that.
\
Promise.all()\ Examples below.
Rendering listJust like react, we will use .map() function.
await render` Here is my headings: ${() => { return "".concat( ...[1,2,3,4,5].map((t) => { return `Promise.all() here is not necessary because there is no asynchronous function inside them
await render` Here is my data ${async () => { const text = `SELECT * FROM table`; const values = []; var record = await pool.query(text, values); return "".concat( ...(await Promise.all( record.rows.map((t) => { return `\
All Rights Reserved. Copyright , Central Coast Communications, Inc.