SlideShare a Scribd company logo
1 of 21
ES2015 –promise
IAN
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.
Promise
A 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)}); // 出錯了
Reference
 http://es6.ruanyifeng.com/#docs/promise
 http://es6.ruanyifeng.com/#docs/module

More Related Content

What's hot

LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
Adam Crabtree
 

What's hot (14)

Unit Testing Front End JavaScript
Unit Testing Front End JavaScriptUnit Testing Front End JavaScript
Unit Testing Front End JavaScript
 
AngularJS Testing Strategies
AngularJS Testing StrategiesAngularJS Testing Strategies
AngularJS Testing Strategies
 
Nagios Conference 2012 - Dave Josephsen - Stop Being Lazy
Nagios Conference 2012 - Dave Josephsen - Stop Being LazyNagios Conference 2012 - Dave Josephsen - Stop Being Lazy
Nagios Conference 2012 - Dave Josephsen - Stop Being Lazy
 
Fork 3.0 JS improvements
Fork 3.0 JS improvementsFork 3.0 JS improvements
Fork 3.0 JS improvements
 
Callbacks and control flow in Node js
Callbacks and control flow in Node jsCallbacks and control flow in Node js
Callbacks and control flow in Node js
 
Better react/redux apps using redux-saga
Better react/redux apps using redux-sagaBetter react/redux apps using redux-saga
Better react/redux apps using redux-saga
 
Lecture04
Lecture04Lecture04
Lecture04
 
4front en
4front en4front en
4front en
 
Promises in iOS development
Promises in iOS developmentPromises in iOS development
Promises in iOS development
 
Async History - javascript
Async History - javascriptAsync History - javascript
Async History - javascript
 
The Ring programming language version 1.7 book - Part 85 of 196
The Ring programming language version 1.7 book - Part 85 of 196The Ring programming language version 1.7 book - Part 85 of 196
The Ring programming language version 1.7 book - Part 85 of 196
 
Let's JavaScript
Let's JavaScriptLet's JavaScript
Let's JavaScript
 
Martin Anderson - threads v actors
Martin Anderson - threads v actorsMartin Anderson - threads v actors
Martin Anderson - threads v actors
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
 

Similar to ES2015 promise

Javascript Promises
Javascript PromisesJavascript Promises
Javascript Promises
intive
 
Java Script Promise
Java Script PromiseJava Script Promise
Java Script Promise
Alok Guha
 
Promises look into the async future
Promises look into the async futurePromises look into the async future
Promises look into the async future
slicejs
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
Chris Saylor
 

Similar to ES2015 promise (20)

JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
The Promised Land (in Angular)
The Promised Land (in Angular)The Promised Land (in Angular)
The Promised Land (in Angular)
 
Promises - Asynchronous Control Flow
Promises - Asynchronous Control FlowPromises - Asynchronous Control Flow
Promises - Asynchronous Control Flow
 
Javascript Promises
Javascript PromisesJavascript Promises
Javascript Promises
 
JavaScript Interview Questions 2023
JavaScript Interview Questions 2023JavaScript Interview Questions 2023
JavaScript Interview Questions 2023
 
Java Script Promise
Java Script PromiseJava Script Promise
Java Script Promise
 
New improvements for web developers - frontend.fi, Helsinki
New improvements for web developers - frontend.fi, HelsinkiNew improvements for web developers - frontend.fi, Helsinki
New improvements for web developers - frontend.fi, Helsinki
 
Process control nodejs
Process control nodejsProcess control nodejs
Process control nodejs
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
 
Promises look into the async future
Promises look into the async futurePromises look into the async future
Promises look into the async future
 
The evolution of java script asynchronous calls
The evolution of java script asynchronous callsThe evolution of java script asynchronous calls
The evolution of java script asynchronous calls
 
非同期javascriptの過去と未来
非同期javascriptの過去と未来非同期javascriptの過去と未来
非同期javascriptの過去と未来
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
 
Callbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptCallbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascript
 
Promises, promises, and then observables
Promises, promises, and then observablesPromises, promises, and then observables
Promises, promises, and then observables
 
Javascript: the important bits
Javascript: the important bitsJavascript: the important bits
Javascript: the important bits
 
Difference between promise-chain and promise.all() in Javascript
Difference between promise-chain and promise.all() in JavascriptDifference between promise-chain and promise.all() in Javascript
Difference between promise-chain and promise.all() in Javascript
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
Deferred
DeferredDeferred
Deferred
 
You promise?
You promise?You promise?
You promise?
 

More from LearningTech (20)

vim
vimvim
vim
 
PostCss
PostCssPostCss
PostCss
 
ReactJs
ReactJsReactJs
ReactJs
 
Docker
DockerDocker
Docker
 
Semantic ui
Semantic uiSemantic ui
Semantic ui
 
node.js errors
node.js errorsnode.js errors
node.js errors
 
Expression tree
Expression treeExpression tree
Expression tree
 
SQL 效能調校
SQL 效能調校SQL 效能調校
SQL 效能調校
 
flexbox report
flexbox reportflexbox report
flexbox report
 
Vic weekly learning_20160504
Vic weekly learning_20160504Vic weekly learning_20160504
Vic weekly learning_20160504
 
Reflection & activator
Reflection & activatorReflection & activator
Reflection & activator
 
Peggy markdown
Peggy markdownPeggy markdown
Peggy markdown
 
Node child process
Node child processNode child process
Node child process
 
20160415ken.lee
20160415ken.lee20160415ken.lee
20160415ken.lee
 
Peggy elasticsearch應用
Peggy elasticsearch應用Peggy elasticsearch應用
Peggy elasticsearch應用
 
Expression tree
Expression treeExpression tree
Expression tree
 
Vic weekly learning_20160325
Vic weekly learning_20160325Vic weekly learning_20160325
Vic weekly learning_20160325
 
D3js learning tips
D3js learning tipsD3js learning tips
D3js learning tips
 
git command
git commandgit command
git command
 
Asp.net MVC DI
Asp.net MVC DIAsp.net MVC DI
Asp.net MVC DI
 

Recently uploaded

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Recently uploaded (20)

Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 

ES2015 promise

  • 2. 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.
  • 3. Promise A 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.
  • 4. 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)
  • 5. 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  });
  • 6. Example1  function timeout(ms) {  return new Promise((resolve, reject) =>  { setTimeout(resolve, ms, 'done'); }  );  }  timeout(100).then((value) => { console.log(value);});
  • 7. 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);} );
  • 8.  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的回調函數將會立刻執行。
  • 9. 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  });
  • 10. Promise.prototype.catch()  Promise.prototype.catch方法是.then(null, rejection)的別名  Syntax:  p.catch(onRejected);  p.catch(function(reason) {  // rejection  });
  • 11.  getJSON("/posts.json").then(function(posts) { // ... }).  catch(function(error) {  // 處理前一個回調函數運行時發生的錯誤  console.log('發生錯誤!', error);}  );
  • 12.  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));
  • 13.  var promise = new Promise(function(resolve, reject) {  throw new Error('test')  });  promise.catch(function(error) {  console.log(error); // Error: test  });
  • 14.  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
  • 15. 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]);
  • 16.  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){ // ... });
  • 17. 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]);
  • 18. 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 () { // ... });
  • 19. Promise.resolve()  var jsPromise = Promise.resolve($.ajax('/whatever.json'));  var p = Promise.resolve('Hello');  p.then(function (s){ console.log(s)});  // Hello
  • 20. Promise.reject()  var p = Promise.reject('出錯了');  p.then(null, function (s){ console.log(s)}); // 出錯了

Editor's Notes

  1. 有了Promise對象,就可以將異步操作以同步操作的流程表達出來,避免了層層嵌套的回調函數。 Promise也有一些缺點。首先,無法取消Promise內部拋出的錯誤,不會反應到外部。第三,當 如果不設置回調函數,Promise處於Pending狀態時,無法得知目前進展到哪一個階段
  2. then方法可以接受兩個回調函數作為參數。第一個回調函數是Promise對象的狀態變為Resolved時調用,第二個回調函數是Promise對象的狀態變為Reject時調用。其中,第二個函數是可選的
  3. Promise對象的錯誤具有「冒泡」性質,會一直向後傳遞,直到被捕獲為止。也就是說,錯誤總是會被下一個catch語句捕獲。
  4. p的狀態由p1、p2、p3決定,分成兩種情況。 (1)只有p1、p2、p3的狀態都變成fulfilled,p的狀態才會變成fulfilled,此時p1、p2、p3的返回值組成一個數組,傳遞給p的回調函數。 (2)只要p1、p2、p3之中有一個被rejected,p的狀態就變成rejected,此時第一個被reject的實例的返回值,會傳遞給p的回調函數。
  5. 上面代碼中,只要p1、p2、p3之中有一個實例率先改變狀態,p的狀態就跟著改變。那個率先改變的Promise實例的返回值,就傳遞給p的回調函數。