JavaScript Notes and Comparisons V2.0

Nexmoe November 1, 2023
This article is an AI translation and may contain semantic inaccuracies.

Differences between Promise and RxJS Observables

Promise

  • Promise is built into JavaScript and requires no extra libraries.
  • A Promise represents a single value that may be available now or in the future.
  • Promises are eager: once resolved, the .then() callback runs immediately.
  • A Promise can only emit a single value.
  • Promises are great for simple async operations that produce one result.

RxJS Observables

  • Observables are part of the RxJS library and require extra dependencies.
  • An Observable represents a stream of values over time.
  • Observables are lazy: nothing happens until you subscribe.
  • Observables can emit multiple values, including zero or many.
  • You can transform and compose Observables with RxJS operators to create custom streams.
  • Observables are great for complex async operations, such as real‑time data streams or event‑driven programming.

References

  1. JavaScript Theory: Promise vs Observable - Medium
  2. angular - What is the difference between Promises and Observables? - Stack Overflow
  3. JavaScript Promises vs. RxJS Observables

A simple template syntax implementation

const name = 'Nexmoe';
const message = 'My name is {{name}} and I\'m {{getAge(20)}} years old.';

function getAge(age) {
  return age;
}

const replacedMessage = message.replace(/\{\{(.*?)\}\}/g, (match, variableOrFunction) => {
  const trimmedValue = variableOrFunction.trim();

  if (trimmedValue.includes('(')) {  // If the placeholder contains parentheses, treat it as a function call with args
    const [functionName, ...args] = trimmedValue.split(/\(|\)/).filter(Boolean);
    const func = eval(functionName);
    return func(...args);
  } else {  // Otherwise treat it as a variable
    return eval(trimmedValue);
  }
});

onsole.log(replacedMessage);

First check whether the placeholder contains parentheses. If it does, treat it as a function call. Use split and a regex to parse the function name and arguments, then use eval to get the function and spread the args into it. The return value becomes the replacement string.

If it doesn’t contain parentheses, treat it as a variable. Use eval to get the variable’s value and return it as the replacement.

⚠️ Note: using eval is risky because it can execute arbitrary JavaScript. Many people advise against it. I plan to explore alternatives later.