Promises.

Slides:



Advertisements
Similar presentations
COMP 121 Week 5: Exceptions and Exception Handling.
Advertisements

11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
Nachos Phase 1 Code -Hints and Comments
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
Errors And How to Handle Them. GIGO There is a saying in computer science: “Garbage in, garbage out.” Is this true, or is it just an excuse for bad programming?
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Interrupts and Exception Handling. Execution We are quite aware of the Fetch, Execute process of the control unit of the CPU –Fetch and instruction as.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
Introduction to Exceptions in Java CS201, SW Development Methods.
ITM 3521 ITM 352 Functions. ITM 3522 Functions  A function is a named block of code (i.e. within {}'s) that performs a specific set of statements  It.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Logical Operators.  Quizzes!  Let's look at the schedule  Logical Operators 2.
JavaScript: Conditionals contd.
BIT116: Scripting Lecture 05
JavaScript Controlling the flow of your programs with ‘if’ statements
User-Written Functions
Parallelism and Concurrency
Lecture 14 Throwing Custom Exceptions
Loops BIS1523 – Lecture 10.
Promises and Asynchronous Programming
Why exception handling in C++?
Lecture 25 More Synchronized Data and Producer/Consumer Relationship
Modularity and Memory Clearly, programs must have access to memory
Error Handling Summary of the next few pages: Error Handling Cursors.
Chapter 14: Exception Handling
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Exceptions 10-Nov-18.
Control Structures - Repetition
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Exception Handling Chapter 9.
Phil Tayco Slide version 1.0 Created Oct 2, 2017
CSE 154 Lecture 22: AJAX.
Functions BIS1523 – Lecture 17.
Python Primer 2: Functions and Control Flow
Conditions and Ifs BIS1523 – Lecture 8.
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Chapter 12 Exception Handling and Text IO
Repetition Structures
Exception Handling Oo28.
Fundamentals of Data Structures
Coding Concepts (Basics)
CS5220 Advanced Topics in Web Programming More Node.js
Lecture 12: The Fetch Api and AJAx
Lecture 12: The Fetch Api and AJAx
CMSC 202 Exceptions 2nd Lecture.
CS333 Intro to Operating Systems
Exceptions 25-Apr-19.
Why we have Counterintuitive Memory Models
Exceptions 22-Apr-19.
CSC 143 Java Errors and Exceptions.
Exceptions 10-May-19.
Computer Science 340 Software Design & Testing
LCC 6310 Computation as an Expressive Medium
Exceptions 5-Jul-19.
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions.
Exception Handling.
Lecture 3 More on Flow Control, More on Functions,
CS5220 Advanced Topics in Web Programming More Node.js
ITM 352 Functions.
Functions Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Threads and concurrency / Safety
Presentation transcript:

Promises

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.

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.

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

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:

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)

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.

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.

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

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.

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

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.

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

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.

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

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

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

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!

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!

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

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.

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

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

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

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

Sources https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-promise-27fc71e77261 https://codeburst.io/javascript-learn-promises-f1eaa00c5461 https://www.promisejs.org/ https://scotch.io/tutorials/javascript-promises-for-dummies https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises https://developers.google.com/web/fundamentals/primers/promises