Skip to content

Web Development

kitiya edited this page Mar 8, 2020 · 16 revisions

HTTP

HTTP Request

  • GET
  • POST
  • PUT
  • DELETE

HTTPS Response

  • 1xx: Information
  • 2xx: Success
  • 3xx: Redirect
  • 4xx: Client errors
  • 5xx: Server errors

JSON

  • JSON.parse(jsonString)
  • JSON.stringnify(jsonObject)

AJAX

componentDidMount() {
  fetch(url) //return a promise (response)
    .then(response => response.json()) //return a promise (users)
    .then(users => { this.setState({myUsers: users}) });
}

The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function.

A promise constructor

let promise = new Promise((resolve, reject) => {
  // the function is executed automatically when the promise is constructed

  // after 1 second signal that the job is done with the result "done"
  setTimeout(() => resolve("done"), 1000);
}

The function passed to new Promise is called the executor. When new Promise is created, the executor runs automatically. It contains the producing code which should eventually produce the result.

When the executor obtains the result, be it soon or late, doesn’t matter, it should call one of these callbacks:

  • resolve(value) — if the job finished successfully, with result value.
  • reject(error) — if an error occurred, error is the error object.

The promise object returned by the new Promise constructor has these internal properties:

  • state — initially "pending", then changes to either "fulfilled" when resolve is called or "rejected" when reject is called.
  • result — initially undefined, then changes to value when resolve(value) called or error when reject(error) is called.

Consumers: then, catch, finally

A Promise object serves as a link between the executor and the consuming functions, which will receive the result or error. Consuming functions can be registered (subscribed) using methods .then, .catch and .finally.

.then

promise.then(
  function(result) { /* handle a successful result */ },
  function(error) { /* handle an error */ }
);
  • The first argument of .then is a function that runs when the promise is resolved, and receives the result.
  • The second argument of .then is a function that runs when the promise is rejected, and receives the error.

Async Await

Simple example

// using promise
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => response.json())
.then(console.log);

// using async/await
async function fetchData() {
  const response = await fetch("https://jsonplaceholder.typicode.com/users");
  const data = await response.json();
  console.log(data);
}

fetchData();

Replacing Promise.all()

urls = [
  "https://jsonplaceholder.typicode.com/posts",
  "https://jsonplaceholder.typicode.com/users",
  "https://jsonplaceholder.typicode.com/photos"
]

// using promise
Promise.all(urls.map(
  url => fetch(url)
    .then( response=>response.json())
    .then( array => {
      console.log("posts", array[0]);
      console.log("users", array[1]);
      console.log("photos", array[2]);
    }
)));

// using async/await
const getData = async function() {
  const [users, posts, albums] = await Promise.all(
    urls.map(async function(url) {
      const response = await fetch(url);
      return response.json();
    })
  );
  
  console.log(users, users);
  console.log(posts, posts);
  console.log(albums, albums);
}
getData();

Clone this wiki locally