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
- Replace
Rx.EMPTYwithfrom(promise). - The
StartandEndlogs are already there — leave them, they reveal the order. - Expected order:
Start → End → Result: DATA.
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');