メインコンテンツにスキップ
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 回の試行後に解決策が利用可能になります