JavaScript - kitiya/react-29 GitHub Wiki
Scope
//TODO
Array
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
Functions
//TODO
Objects
// TODO
Pass by value vs pass by reference
// TODO
JavaScript Flasy
There are 7 falsy values in JavaScript.
false:0: the number zero0n: BigInt"",'', ````: an empty stringnull: the absence of any valueundefined: undefined - the primitive valueNaN: not a number
Type Coercion
AJAX
componentDidMount() {
fetch(url) //return a promise (response)
.then(response => response.json()) //return a promise (users)
.then(users => { this.setState({myUsers: users}) });
}
Promise
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 resultvalue.reject(error)โ if an error occurred,erroris 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โ initiallyundefined, then changes tovaluewhenresolve(value)called orerrorwhenreject(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
.thenis a function that runs when the promise is resolved, and receives the result. - The second argument of
.thenis 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();
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);
}
}