es2015 promise

21
ES2015 – promise IAN

Upload: learningtech

Post on 20-Feb-2017

352 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: ES2015 promise

ES2015 – promiseIAN

Page 2: ES2015 promise

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.

Page 3: ES2015 promise

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.

Page 4: ES2015 promise

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 )

Page 5: ES2015 promise

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 });

Page 6: ES2015 promise

Example1

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

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

}

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

Page 7: ES2015 promise

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);}

);

Page 8: ES2015 promise

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 的回調函數將會立刻執行。

Page 9: ES2015 promise

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 });

Page 10: ES2015 promise

Promise.prototype.catch()

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

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

Page 11: ES2015 promise

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

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

);

Page 12: ES2015 promise

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));

Page 13: ES2015 promise

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

});

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

Page 14: ES2015 promise

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

Page 15: ES2015 promise

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]);

Page 16: ES2015 promise

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){ // ... });

Page 17: ES2015 promise

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]);

Page 18: ES2015 promise

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 () { // ... });

Page 19: ES2015 promise

Promise.resolve()

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

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

Page 20: ES2015 promise

Promise.reject()

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