Promise

想像有一位超級歌星,粉絲日以繼夜關心專輯什麼時候出,這位超級歌星很煩惱,因此想出了一個辦法,讓粉絲追蹤他的 IG ,若有任何關於他的消息都可以第一時間知道。 在編寫程式碼也會遇到一樣的問題: 1. 生產程式碼:作一些事需要時間,像是加載腳本,腳色是歌手。 2. 消費程式碼:知道生產程式碼的結果,不論有沒有成功,腳色是粉絲。 3. promise 是連接 2 者的橋樑,生產程式碼的結果會保證傳到每個消費程式碼,腳色是 IG。

// syntax,executor 是生產程式碼,最終會產生結果,傳到 promise,promise 物件有 2 個內部屬性,
// state 描述 promise 狀態,一開始 pedding => fullfilled or rejected
// result 任意值,一開始 undefined => value or error
let promise = new Promise(function(resolve, reject) {
  // executor (生产者代码,"singer")
});

Consumers: then, catch, finally

消費程式碼可以得知生產結果,透過 .then, .catch and .finally等方法。

then

catch

finally

Example: loadScript

Promises

Callbacks

Promises allow us to do things in the natural order. First, we run loadScript(script), and .then we write what to do with the result.

We must have a callback function at our disposal when calling loadScript(script, callback). In other words, we must know what to do with the result before loadScript is called.

We can call .then on a Promise as many times as we want. Each time, we’re adding a new “fan”, a new subscribing function, to the “subscription list”. More about this in the next chapter: Promises chaining.

There can be only one callback.

Last updated

Was this helpful?