Wait for slow work

INPUT · Slides

Boxes of promises (Promise)

01 / 05

Operations that take time

Fetching data from a server or waiting on a timer takes time. If the whole program froze while waiting, the interface would lock up.

A Promise acts like a voucher that says, "I don't have the result yet, but I promise to give it to you later".

02 / 05

Creating a box and resolving the value

You make a Promise with new Promise((resolve) => { ... }).

When work finishes, you call resolve(resultValue). This marks the promise as fulfilled.

const promise = new Promise((resolve) => {  resolve("Done!");});

03 / 05

Receiving the result with then

To receive the promised result, use .then((val) => { ... }).

When the promise resolves, your callback function runs with the value.

const promise = new Promise((resolve) => {  resolve("Gift");});promise.then((item) => {  console.log(item);});

Result

Gift

04 / 05

Combining with timers

Resolving inside a setTimeout simulates real asynchronous delays.

While waiting, the rest of your program continues running — this is the essence of asynchronous JavaScript.

console.log("Start");const wait = new Promise((resolve) => {  setTimeout(() => {    resolve("Delivered later");  }, 10);});wait.then((msg) => {  console.log(msg);});console.log("End");

Result

Start
End
Delivered later

05 / 05

Check the key points

Let us review the ideas:

  • new Promise((resolve) => { ... }) creates a promise
  • When done, call resolve(value) to deliver the result
  • .then((value) => { ... }) receives the resolved outcome

Let us practice using promises!