முக்கிய உள்ளடக்கத்திற்குச் செல்லவும்
eLearner.app
தொகுதி 7 · பாடம் 1 இன் 4பாடத்திட்டத்தில் 25/32~12 min
தொகுதி பாடங்கள் (1/4)

வாக்குறுதிகள்: அவை என்ன

A Promise is a value that represents the result of an operation that will finish in the future. It can be in one of three states:

  • pending — the operation is still in progress
  • fulfilled — it finished successfully, there is a value
  • rejected — it failed, there is an error

Once it leaves the pending state, it is "settled" forever.

Creating a resolved Promise

The two most common ways — you will almost never create a Promise "by hand" with the constructor:

JS
const p1 = Promise.resolve(42);
const p2 = Promise.reject(new Error('oops'));

Reading the result: .then / .catch

JS
Promise.resolve(10).then((v) => {
  console.log(v); // 10
});

Promise.reject(new Error('no')).catch((e) => {
  console.log(e.message); // 'no'
});

.then receives a function that is called with the resolved value. .catch receives a function called with the error in case of rejection.

Chaining

Every .then returns in turn a Promise: you can chain them to transform the value step by step.

JS
Promise.resolve(5)
  .then((n) => n * 2)
  .then((n) => n + 1)
  .then((n) => console.log(n)); // 11

If any of the .then throws (or returns a Promise that fails), execution jumps to the first subsequent .catch.

Constructor (rare)

JS
const p = new Promise((resolve, reject) => {
  if (Math.random() > 0.5) resolve('ok');
  else reject(new Error('no'));
});

You will use it only when you need to "promisify" something that uses callbacks (e.g. old DOM APIs or setTimeout).

Try it

உடற்பயிற்சி#js.m7.l1.e1
முயற்சிகள்: 0ஏற்றுகிறது…

Define `promisedVersion(n)` that, given a number, returns a Promise resolved with double of n.

எடிட்டரை ஏற்றுகிறது…
குறிப்பைக் காட்டு

return Promise.resolve(n * 2)

3 முயற்சிகளுக்குப் பிறகு தீர்வு கிடைக்கும்

Review exercise

உடற்பயிற்சி#js.m7.l1.e2
முயற்சிகள்: 0ஏற்றுகிறது…

Define `incrementThree(p)` that receives a Promise of a number and returns a Promise of the number + 3. Use a .then chain.

எடிட்டரை ஏற்றுகிறது…
குறிப்பைக் காட்டு

p.then((n) => n + 3)

3 முயற்சிகளுக்குப் பிறகு தீர்வு கிடைக்கும்