Presentation is loading. Please wait.

Presentation is loading. Please wait.

Promises.

Similar presentations


Presentation on theme: "Promises."— Presentation transcript:

1 Promises

2 Why do we need Promises? Why is this important?
Think about a website that loads data from an API then processes and formats the data to display to the user. If we try to process and format our data before the API has even fetched the information, we’re either going to get an error or a blank website. By using a Promise, we can ensure that the API data isn’t processed/formatted until after our API call has succeeded.

3 Why Promise is this important?
Why is this important? Consider the following synchronous JavaScript function to read a file and parse it as JSON. It is simple and easy to read, but you wouldn't want to use it in most applications as it is blocking. This means that while you are reading the file from disk (a slow operation) nothing else can happen. To make our application performant and responsive, we need to make all the operations that involve IO be asynchronous. The simplest way to do this would be to use a callback. However, a naive implementation will probably go wrong as follow.

4 Using callback to perform IO asynchronous
The extra callback parameter confuses our idea of what is input and what is the return value. It doesn't work at all with control flow primitives. It doesn't handle errors thrown by JSON.parse

5 Using callback to perform IO asynchronous
We need to handle errors thrown by JSON.parse but we also need to be careful not to handle errors thrown by the callback function. By the time we've done all of this our code is a mess of error handling:

6 Using callback to perform IO asynchronous
Despite all this mess of error handling code, we are still left with the problem of the extra callback parameter hanging around. Promises help you naturally handle errors, and write cleaner code by: Not having callback parameters, and without modifying the underlying architecture (i.e. you can implement them in pure JavaScript and use them to wrap existing asynchronous operations)

7 What is a Promise? A promise is an object that may produce a single value some time in the future: either a resolved value, or a reason that it’s not resolved (e.g., a network error occurred). In JavaScript, a Promise represents the eventual result of an asynchronous operation. Think of it as a placeholder. This placeholder is essentially an object on which we can attach callbacks. Promises (like callbacks) allow us to wait on certain code to finish execution prior to running the next bit of code.

8 What is a Promise? Lets think about promise as the following scenario
"Imagine you are a kid. Your mom promises you that she'll get you a new phone next week.“ You don't know if you will get that phone until next week. Your mom can either really buy you a brand new phone, or stand you up and withhold the phone if she is not happy :(. That is a promise. A promise has 3 states. They are: Promise is pending: You don't know if you will get that phone until next week. Promise is resolved: Your mom really buy you a brand new phone. Promise is rejected: You don't get a new phone because your mom is not happy.

9 Promise’s States A promise may be in one of 3 possible states
Fulfilled — Operation has completed and the Promise has a value onFulfilled() will be called (e.g., resolve() was called) Rejected — Operation has completed with an error or failed. onRejected() will be called (e.g., reject() was called) Pending — Asynchronous operation has not completed yet not yet fulfilled or rejected

10 Settled or Pending? A promise is settled if it is not pending (it has been resolved or rejected). ). Once a Promise has settled, it is settled for good. It cannot transition to any other state. Sometimes people use resolved and settled to mean the same thing: not pending. Promise users can attach callbacks to handle the fulfilled value or the reason for rejection.

11 Promise with Callback Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function. E.g., instead of an old-style function that expects two callbacks, and calls one of them on eventual completion or failure: …modern functions return a promise you can attach your callbacks to instead: …or simply: We call this an asynchronous function call. This convention has several advantages. function successCallback(result) { console.log("It succeeded with " + result); } function failureCallback(error) { console.log("It failed with " + error); doSomething(successCallback, failureCallback); const promise = doSomething(); promise.then(successCallback, failureCallback); doSomething().then(successCallback, failureCallback);

12 Asynchronous Function Call Advantages
Guarantees Unlike old-style passed-in callbacks, a promise comes with some guarantees: Callbacks will never be called before the completion of the current run of the JavaScript event loop. Callbacks added with .then even after the success or failure of the asynchronous operation, will be called, as above. Multiple callbacks may be added by calling .then several times, to be executed independently in insertion order. But the most immediate benefit of promises is chaining. Chaining A common need is to execute two or more asynchronous operations back to back, where each subsequent operation starts when the previous operation succeeds, with the result from the previous step. We accomplish this by creating a promise chain.

13 When Does Promise start working?
Promises are eager, meaning that a promise will start doing whatever task you give it as soon as the promise constructor is invoked. If you need lazy, check out observables or tasks

14 Working With Promises Most of the time when working with Promises, you will be consuming already-created promises that have been returned from functions. However, you can also create a promise with it’s constructor. Here’s what a simple Promise might look like: runFunction().then(successFunc, failureFunc); In the above example, we first invoke the runFunction() function. Since runFunction() returns a promise, only when the Promise is settled can our successFunc, or failureFunc function run. If the Promise is Fulfilled, our sucessFunc is invoked. If the Promise fails, our failureFunc is invoked.

15 Creating A Promise Example
To implement the following example in Javascript: "Imagine you are a kid. Your mom promises you that she'll get you a new phone next week.“ We write the following. /* ES5 */ var isMomHappy = false; // Promise var willIGetNewPhone = new Promise( function (resolve, reject) { if (isMomHappy) { var phone = { brand: 'Samsung', color: 'black' }; resolve(phone); // fulfilled } else { var reason = new Error('mom is not happy'); reject(reason); // reject } } );

16 Creating A Promise Example
The code is quite expressive in itself. We have a boolean isMomHappy, to define if mom is happy. We have a promise willIGetNewPhone. The promise can be either resolved (if mom get you a new phone) or rejected(mom is not happy, she doesn't buy you one). There is a standard syntax to define a new Promise, refer to MDN documentation, a promise syntax look like this. // promise syntax look like this new Promise(/* executor*/ function (resolve, reject) { ... } ); What you need to remember is, when the result is successful, call resolve(your_success_value), if the result fails, call reject(your_fail_value) in your promise. In our example, if mom is happy, we will get a phone. Therefore, we call resolve function with phone variable. If mom is not happy, we will call reject function with a reason reject(reason);

17 Consuming Promises Now that we have the promise, let's consume it.
.// call our promise var askMom = function () { willIGetNewPhone .then(function (fulfilled) { // yay, you got a new phone console.log(fulfilled); // output: { brand: 'Samsung', color: 'black' } }) .catch(function (error) { // oops, mom don't buy it console.log(error.message); // output: 'mom is not happy' }); }; askMom();

18 Consuming Promises We have a function call askMom. In this function, we will consume our promise willIGetNewPhone. We want to take some action once the promise is resolved or rejected, we use .then and .catch to handle our action. In our example, we have function(fulfilled) { ... } in .then. What is the value of fulfilled? The fulfilled value is exactly the value you pass in your promise resolve(your_success_value). Therefore, it will be phone in our case. We have function(error){ ... } in .catch. What is the value of error? As you can guess, the error value is exactly the value you pass in your promise reject(your_fail_value). Therefore, it will be reason in our case. Let's run the example and see the result!

19 Chaining Promises Promises are chainable.
Let's say, you, the kid, promise your friend that you will show them the new phone when your mom buy you one. That is another promise. Let's write it!

20 Chaining Promises // 2nd promise var showOff = function (phone) {
return new Promise( function (resolve, reject) { var message = 'Hey friend, I have a new ' + phone.color + ' ' + phone.brand + ' phone'; resolve(message); } ); };

21 Chaining Promises Notes:
In this example, you might realize we didn't call the reject. It's optional. We can shorten this sample like using Promise.resolve instead.

22 Chaining Promises // shorten it ... // 2nd promise
var showOff = function (phone) { var message = 'Hey friend, I have a new ' + phone.color + ' ' + phone.brand + ' phone'; return Promise.resolve(message); };

23 Chaining Promises // shorten it ... // 2nd promise
var showOff = function (phone) { var message = 'Hey friend, I have a new ' + phone.color + ' ' + phone.brand + ' phone'; return Promise.resolve(message); }; Let's chain the promises. You, the kid can only start the showOff promise after the willIGetNewPhone promise

24 Chaining Promises // shorten it ... // 2nd promise
var showOff = function (phone) { var message = 'Hey friend, I have a new ' + phone.color + ' ' + phone.brand + ' phone'; return Promise.resolve(message); }; Let's chain the promises. You, the kid can only start the showOff promise after the willIGetNewPhone promise

25 Chaining Promises // call our promise var askMom = function () {
willIGetNewPhone .then(showOff) // chain it here .then(function (fulfilled) { console.log(fulfilled); // output: 'Hey friend, I have a new black Samsung phone.' }) .catch(function (error) { // oops, mom don't buy it console.log(error.message); // output: 'mom is not happy' }); };

26 Sources


Download ppt "Promises."

Similar presentations


Ads by Google