Skip to content

Instantly share code, notes, and snippets.

@smtx
Last active December 3, 2019 09:38
Show Gist options
  • Save smtx/1812b89fc7e08c46b69eeb6770424168 to your computer and use it in GitHub Desktop.
Save smtx/1812b89fc7e08c46b69eeb6770424168 to your computer and use it in GitHub Desktop.

JS2-Week3

Callbacks

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Title</title>
    </head>
    <body>
        <button id="myButton">I'm a button</button>
        <script src="index.js"></script>
    </body>
</html>
let btn = document.getElementById('myButton');

btn.addEventListener('click', clickButton);

function clickButton() {
  console.log('button clicked');
}
const logCall = function() {
  console.log('logCall was called back.')
}

setTimeout(logCall, 3000);
setTimeout(function() {
  console.log('logCall was called back.')
}, 3000);
let tvShows = [
  {name: 'Breaking Bad', genre: 'Thriller', imdb_rating: 9.5},
  {name: 'Firefly', genre: 'Sci-Fi', imdb_rating: 9.0},
  {name: 'Friends', genre: 'Comedy', imdb_rating: 8.9 },
  {name: 'Narcos', genre: 'Crime', imdb_rating: 8.8},
  {name: 'Black Mirror', genre: 'Sci-Fi', imdb_rating: 8.8}
];

let processTVShows = function(data, callback) {
  for (let i = 0; i < data.length; i++) {
    const tvShow = data[i];
    if ( tvShow.genre === 'Sci-Fi' ) {
      callback(tvShow)
    }
  }
}

processTVShows(tvShows, function(filteredTvShow){
  console.log(filteredTvShow);
})

task Call processTVShows again and create a callback function that shows in console the Sci Fi Tv Show with best rating

Synchronous vs Asynchronous

Phone vs Whatsapp

setTimeout(function() {
  console.log('logCall was called back.')
}, 3000);
function logCall() {
  setTimeout(function() {
    console.log('logCall was called back.');
  }, 3000);
}

function anotherCall() {
  console.log('anotherCall here.');
}

logCall();
anotherCall();

Promises

a promise is a container for a future value Promises are a new(ish) feature of JavaScript. They allow for writing easier to understand code when dealing with asynchronous functions.

[image:3A67FE00-4F0F-40B8-A05D-9515E275CD40-28840-00021217D8101CCF/687474703a2f2f6578706c6f72696e676a732e636f6d2f6573362f696d616765732f70726f6d697365732d2d2d2d70726f6d6973655f7374617465735f73696d706c652e6a7067.jpg]

Promises are more “abstract” than anything we have covered so far. They are a data structure that represents some result that is going to happen in the future. The result starts off as being unknown (pending) as the code has not completed yet. The result can then move to be successful (fulfilled) or failed (rejected). The API is very simple. When you have a Promise, you can attach a .then method with a callback and/or a .catch method with a callback. If the promise is successful, then the function in the .then callback is called. If it fails, then the .catch callback is called.

let logCall = new Promise(function(resolve, reject) {
  setTimeout(function() {
	  console.log('logCall was called back.')
    resolve();
  }, 3000);	
})

console.log(logCall); 

console.log(typeof logCall);
function anotherCall() {
  console.log('anotherCall here.');
}

logCall.then(anotherCall);

task

Delay with a promise

Delay with a promise

The built-in function setTimeout uses callbacks. Create a promise-based alternative. The function delay(ms) should return a promise. That promise should resolve after ms milliseconds, so that we can add .then to it, like this:

function delay(ms) {
  // your code
}

delay(3000).then(() => alert('runs after 3 seconds'));

Exercises Complete the exercises in A Pen by Ali Smith

AJAX

Client/Server architecture

A server is a device or program that provides functionality to other programs or devices. There are database servers, mail servers, game servers, etc. The vast majority of these servers are accessed over the internet. They can take the form of industrial server farms that provide a service to millions of users (used by Facebook, Google, etc.), to personal servers for storing your files. The server communicates with clients. A client can be a web browser, a Slack app, your phone, etc. Client–server systems use the request–response model: a client sends a request to the server, which performs some action and sends a response back to the client, typically with a result or acknowledgement. [image:1C7BB104-638C-4FC1-B86A-CA856F2AF10C-28840-00021217D7AB3025/client-server.png]

HTTP Requests

A server stores the data, and the client (other programs or computers) requests data or sends some of its own. But how do they talk to each other? For the client and the server to communicate they need an established language (a protocol). Which is what HTTP (Hypertext Transfer Protocol) is for. It defines the methods you can use to communicate with a server and indicate your desired actions on the resources of the server. There are two main types of requests: GET and POST. Request type Description GET Ask for a specified resource (e.g. show me that photo) POST Send content to the server (e.g. post a photo) HTTP is the language of the internet. In our case we’re using Javascript, but you can send HTTP requests with other laguages as well.

What is AJAX?

AJAX is a technique for implementing client-server communication in the browser. Typically, the server holds the data, and only sends it to the client (web page) when there’s a request. AJAX requests are sent after the page has loaded, usually in response to an action by the user. For example when the user clicks a button, some JavaScript will trigger an AJAX request to fetch data.

Fetch

JavaScript can send network requests to the server and load new information whenever is needed. For example, we can use a network request to:

  • Submit an order,
  • Load user information,
  • Receive latest updates from the server,
  • …etc. …And all of that without reloading the page!

There’s an umbrella term “AJAX” (abbreviated Asynchronous JavaScript And XML) for network requests from JavaScript. We don’t have to use XML though: the term comes from old times, that’s why that word is there. You may have heard that term already. There are multiple ways to send a network request and get information from the server. The fetch() method is modern and versatile, so we’ll start with it. It’s not supported by old browsers (can be polyfilled), but very well supported among the modern ones.

The basic syntax is: fetch(url)

fetch('https://migracode.s3.eu-west-3.amazonaws.com/quote_1.txt')

const p = fetch(‘https://migracode.s3.eu-west-3.amazonaws.com/quote_1.txt')

console.log(p)
p.then((result) => console.log(result))
const p = fetch(‘https://migracode.s3.eu-west-3.amazonaws.com/quote_1.txt')

const p2 = p.then((result) => {
  return result.text();
})

console.log(p2);
const p = fetch(‘https://migracode.s3.eu-west-3.amazonaws.com/quote_1.txt')

const p2 = p.then((result) => {
  return result.text();
})

p2.then(result => console.log(result))
fetch(‘https://migracode.s3.eu-west-3.amazonaws.com/quote_1.txt')
  .then(result=> result.text())
  .then(result => console.log(result))

The browser starts the request right away and returns a promise that the calling code should use to get the result. Getting a response is usually a two-stage process. First, thepromise, returned byfetch, resolves with an object of the built-in class as soon as the server responds with headers. Response At this stage we can check HTTP status, to see whether it is successful or not, check headers, but don’t have the body yet. The promise rejects if the fetch was unable to make HTTP-request, e.g. network problems, or there’s no such site. Abnormal HTTP-statuses, such as 404 or 500 do not cause an error. We can see HTTP-status in response properties:

  • status – HTTP status code, e.g. 200.
  • ok – boolean, true if the HTTP status code is 200-299.

Second, to get the response body, we need to use an additional method call. Response provides multiple promise-based methods to access the body in various formats:

  • response.text() – read the response and return as text,
  • response.json() – parse the response as JSON

Task Get 3 Quotes and show as paragraphs (

) (https://migracode.s3.eu-west-3.amazonaws.com/quote_[1,2,3].txt

fetch(‘https://migracode.s3.eu-west-3.amazonaws.com/migracode.json').then(response => response.json()).then(json_response => console.log(json_response))


Task: Same as previous task but build a list of Migracode courses with the result of the fetch.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment