Fake Promise with setTimeout

Image of Author
October 11, 2022 (last updated October 18, 2022)

TL;DR

function fakePromise(data) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(data), 1000);
  });
}

const p = fakePromise("wow");
p.then((x) => console.log(x)); // 'wow'

Explanation

Promises take time to resolve. So, the Promise constructor passes in a resolve callback into the body of the constructor and returns void. The point is that, when the body is ready, it can call resolve, passing it any desired payload. This data will get picked up later on by any then or await call.

setTimeout will execute the provided function after the provided number of milliseconds. This is the way we are mimicking a real-world delay.

In conclusion, the return of fakePromise is a promise in a pending state. After some number of milliseconds defined in setTimeout, the resolve callback gets called with the provided data. That data will be the result in subsequent then or await calls.