BACK
Lessons8. from: Promises
Lessons · 08

8. from: Promises

RxJS and Promises get along

A Promise is the standard way to handle an asynchronous value in JavaScript. It's a great fit for a single result (an HTTP response, for instance). RxJS can "wrap" a Promise in an Observable so you can keep working in one consistent style.

What from(promise) does

The resulting Observable emits one value (the Promise's result) and then calls complete right away. If the Promise rejects, you get an error signal instead.

The golden rule of async

In JavaScript, all the synchronous code runs first. Only afterward come the contents of Promises, timers, and other microtasks. So even when a Promise is already "ready" (Promise.resolve(...)), its handler joins the queue and runs after the nearby synchronous lines.

The order in this lesson

First Start prints, then End, and only then Result: DATA. That's normal and expected.

Your task

  1. Replace Rx.EMPTY with from(promise).
  2. The Start and End logs are already there — leave them, they reveal the order.
  3. Expected order: Start → End → Result: DATA.
Solution spoiler · click to reveal
const { from } = Rx;

console.log('Start');

const promise = Promise.resolve('DATA');
const result$ = from(promise);

result$.subscribe(value => {
  console.log('Result: ' + value);
});

console.log('End');
script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...