SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

La actualidad más candente

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

La actualidad más candente (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 a 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 a 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?
 

Más de 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
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 

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)}); // 出錯了

Notas del editor

  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的回調函數。