Skip to content

JavaScript

kitiya edited this page Mar 8, 2020 · 4 revisions

//TODO

map()

const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const double = nums.map(num => num * 2); // [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

filter()

const fiveUp = nums.filter(num => num >= 5); // [5, 6, 7, 8, 9]

reduce()

Syntax reduce(function, initialValue)

const initialValue = 0;
const total = nums.reduce((accumulator, num) => {return accumulator + num;}, initialValue); // 55

Other Resources

//TODO

// TODO

Pass by value vs pass by reference

// TODO

JavaScript Flasy

There are 7 falsy values in JavaScript.

  • false:
  • 0: the number zero
  • 0n: BigInt
  • "", '', ````: an empty string
  • null: the absence of any value
  • undefined: undefined - the primitive value
  • NaN: not a number

Type Coercion

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.

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

Multiple URL Requests

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 [posts, users, photos] = await Promise.all(
    urls.map(async function(url) {
      const response = await fetch(url);
      return response.json();
    })
  );

  console.log(posts, posts);  
  console.log(users, users);
  console.log(photos, photos);
}
getData();

using for...of...

const getData3 = async function() {
  const arrayOfPromises = urls.map(url => fetch(url));
  for await (let request of arrayOfPromises) {
    const data = await request.json();
    console.log(data);
  }
}

Clone this wiki locally