From Promiseland
From Promiseland
Let the adventure begin!
Before we get to the land of Observables, let's depart from Promiseland (in all fun, you can absolutely use Promises and async/await with Observables).
A Promise is a promise
const p = new Promise((resolve) => {
setTimeout(() => {
resolve('Hello from Promiseland!');
}, 1000);
});
p.then((value) => console.log(value));
See the example on codesandbox
Let's quickly review:
- First, we create a new
Promise. - The
constructor()function requires a single parameter, the executor function. - The executor is a function that receives two functions as parameters — first, the
resolutionFuncfunction, and second, therejectionFunfunction. - When newed-up, the
constructor()function returns a new promise object. - Within the
resolutionFuncwe have created a new timeout that will invoke theresolve()function provided after 1000 ms. - Finally, we log out the value produced using the
.then()method on the promise object.
A few things to note:
- First, promises are always asynchronous (and thus a microtask).
- Second, the promise resolves after 1 second.
- Third, we are not currently handling an potential errors. But, we could use the
catch()method to do so.