ES2015 promise

Preview:

Citation preview

ES2015 – promiseIAN

Promise

The Promise object is used for deferred and asynchronous computations. A Promise represents an operation that hasn't completed yet, but is expected in the future.

Syntax new Promise(executor); new Promise(function(resolve, reject) { ... });

Parameters

executor Function object with two arguments resolve and reject. The first argument fulfills

the promise, the second argument rejects it. We can call these functions once our operation is completed.

PromiseA Promise is in one of these states: pending: initial state, not fulfilled or rejected. fulfilled: meaning that the operation completed successfully. rejected: meaning that the operation failed.

Promise

Pending 、 Resolved ( Fulfilled )、 Rejected 。 var promise = new Promise(function(resolve, reject) {

// ... some code if (/* asyc success*/){

resolve(value); } else { reject(error); }

}); resolve 函數的作用是,將 Promise 對象的狀態從「未完成」變為「成功」(即從 Pending 變為

Resolved ) reject 函數的作用是,將 Promise 對象的狀態從「未完成」變為「失敗」(即從 Pending 變為

Rejected )

Promise - then

The then() method returns a Promise. It takes two arguments, both are callback functions for the success and failure cases of the Promise.

Syntax: p.then(onFulfilled, onRejected);

p.then(function(value) { // fulfillment }, function(reason) { // rejection });

Example1

function timeout(ms) { return new Promise((resolve, reject) =>

{ setTimeout(resolve, ms, 'done'); } );

}

timeout(100).then((value) => { console.log(value);});

Example2 var getJSON = function(url) {

var promise = new Promise(function(resolve, reject){ var client = new XMLHttpRequest(); client.open("GET", url); client.onreadystatechange = handler; client.responseType = "json"; client.setRequestHeader("Accept", "application/json"); client.send();

function handler() { if (this.status === 200) {

resolve(this.response); } else {

reject(new Error(this.statusText)); }

}; }); return promise;};

getJSON(“/posts.json”).then( function(json) { console.log(‘Contents: ’ + json);},

function(error) { console.error(‘something was wrong.', error);}

);

var p1 = new Promise(function(resolve, reject){ // ... }); var p2 = new Promise(function(resolve, reject){ // ... resolve(p1); })

p1 的狀態就會傳遞給 p2 ,也就是說, p1 的狀態決定了 p2 的狀態。如果p1 的狀態是 Pending ,那麼 p2 的回調函數就會等待 p1 的狀態改變;如果 p1 的狀態已經是 Resolved 或者 Rejected ,那麼 p2 的回調函數將會立刻執行。

Chaining Because the then method returns a Promise, you can easily chain then calls.

var p2 = new Promise(function(resolve, reject) { resolve(1); });

p2.then(function(value) { console.log(value); // 1 return value + 1; }).then(function(value) { console.log(value); // 2 });

p2.then(function(value) { console.log(value); // 1 });

Promise.prototype.catch()

Promise.prototype.catch 方法是 .then(null, rejection) 的別名 Syntax: p.catch(onRejected);

p.catch(function(reason) { // rejection });

getJSON("/posts.json").then(function(posts) { // ... }). catch(function(error) {

// 處理前一個回調函數運行時發生的錯誤 console.log(' 發生錯誤! ', error);}

);

p.then((val) => console.log("fulfilled:", val)) .catch((err) => console.log("rejected:", err));

// 等同於 p.then((val) => console.log(fulfilled:", val)) .then(null, (err) => console.log("rejected:", err));

var promise = new Promise(function(resolve, reject) { throw new Error('test')

});

promise.catch(function(error) { console.log(error); // Error: test });

var promise = new Promise(function(resolve, reject) { resolve("ok"); throw new Error('test');

});

promise.then(function(value) { console.log(value) }) .catch(function(error) { console.log(error) });

//Output: ok

Promise.all()

The Promise.all(iterable) method returns a promise that resolves when all of the promises in the iterable argument have resolved.

Syntax Promise.all(iterable);

Parameters Iterable : An iterable object, such as an Array…

EX.var p = Promise.all([p1,p2,p3]);

var promises = [2, 3, 5, 7, 11, 13].map(function(id){ return getJSON("/post/" + id + ".json");

});

Promise.all(promises).then(function(posts) { // ... }).catch(function(reason){ // ... });

Promise.race()

The Promise.race(iterable) method returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects, with the value or reason from that promise.

Syntax Promise.race(iterable);

EX.var p = Promise.race([p1,p2,p3]);

Promise.resolve()

The Promise.reject(reason) method returns a Promise object that is rejected with the given reason. Syntax

Promise.reject(reason); Parameters

reason Reason why this Promise rejected.

var p = Promise.resolve(); p.then(function () { // ... });

Promise.resolve()

var jsPromise = Promise.resolve($.ajax('/whatever.json'));

var p = Promise.resolve('Hello'); p.then(function (s){ console.log(s)}); // Hello

Promise.reject()

var p = Promise.reject(' 出錯了 '); p.then(null, function (s){ console.log(s)}); // 出錯了