console.log("Good morning!")
function cookPorrage(){
console.log("I am cooking")
}
function addCoffeeBeans(){
console.log("beans added")
}
function makeCoffee(){
addCoffeeBeans()
}
function breakfast(){
cookPorrage()
makeCoffee()
console.log("All good this far")
}
setTimeout(function enjoy(){console.log("Enjoy")},10)
$.on('button', 'click', function onClick() {
setTimeout(function timer() {
console.log('You clicked the button!');
breakfast();
}, 2000);
});
Loupe: no support for arrow functions, demo works the best with named functions
a programming paradigm that uses a single thread (event loop) of execution and relies on events to manage concurrency
function b(){console.log("moi!")}
function a(cb){cb()}
a(b);
console.log("Hello");
setTimeout(console.log, 1000,"me");
console.log("it's")
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
// the transfer complete
if (xhr.readyState == 4) {
// the transfer successful
if (xhr.status == 200) {
// the transferred data handled here
}
else {
// handle the error
// error text in the property xhr.statusText
}
}
}
xhr.open("GET", url, true);
xhr.send();
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = handlerFunction;
xhr.open('GET', url, true);
xhr.send();
JSON stands for JavaScript Object Notation. It
supports two structures:
{
"artist":"U2",
"timestamp":"2011-09-07 21:14:02.102805",
"tags":[
[ "rock", "100"],
[ "U2", "100" ],
]
}
[ {"type": "joke",
"question": "Why did the tomato turn red?",
"answer": "Because it saw the salad dressing!",
"category": "food" },
{"type": "meme",
"title": "When you finally finish debugging your code",
"image_url": "https://i.imgur.com/j9tegoL.jpg",
"category": "programming" },
{"type": "pun",
"text": "Reading a book about anti-gravity. It's impossible to put down!",
"category": "science" }]
Promise chain formed of then/catches that return
new Promise((✅, ❌)=>✅)
.then(✅[, ❌])
.then(✅[, ❌])
.then(✅[, ❌])
.then(✅[, ❌])
.catch( ❌) // == .then(null,❌)
function resolved(result){ console.log('Resolved'); return "success";}
function rejected(result) {console.error(result); return "fail";}
Promise.resolve("success").then(resolved); //Promise { <state>: "fulfilled", <value>: "success" }
Promise.reject(new Error("fail")).then(null, rejected); //Promise {<fulfilled>: 'fail'}
Promise.reject(new Error("fail")).catch(rejected); //Promise { <state>: "fulfilled",<value>: "fail" }
Promise.reject(new Error("fail")); //Promise { <state>: "rejected", <reason>:Error }
Promise.reject(new Error("fail")).
catch(err=>console.log(err)); //Promise { <state>: "fulfilled",
//<value>: undefined }
fetch("https://get.geojs.io/v1/ip/country.json")
.then(function(response) {
return response.json();
})
.then(function(data) {
console.log(JSON.stringify(data));
})
.catch(err=>console.log(`fetch err :${err}`));
Defined by using async keyword in a function
async function foo(){}; // as conventional f
const bar = async () => {} ; // as arrow f
(async () => { /* ... */})();
Below, the value of the first await expression is that of the resolved response, and the second, the parsed json. Parsing may take time.
const fetch = require('node-fetch');
const url ='https://jsonplaceholder.typicode.com/todos/1';
(async ()=>{ //as IIFE
let response = await fetch(url); //the 1st
let parsed = await response.json(); //the 2nd
console.log(parsed);
})()
Starts multiple Promises in parallel and waits for them all to finish.
After all the Promises are fulfilled, returns a single Promise, that contains resolved values as an array:
const proms = [1, 2, 3].map(val => Promise.resolve(val));
Promise.all(proms)
.then(res=>console.log(res, typeof res, Array.isArray(res)));
// Array [1, 2, 3] 'object' true
However, Promise.all() rejects if any of the Promises rejects.
More here.
Time consumption of await calls inside async block is got as a sum.
Promise.all() makes the calls concurrently, thus, the time approaches the time spent by the longest call:
First fetching and then json parsing are done concurrently with Promise.all(). An array of Promises (fetch returns promises) is passed as an input parameter.
const url1 = 'https://jsonplaceholder.typicode.com/todos/1';
const url2 = 'https://jsonplaceholder.typicode.com/todos/2'
// Fetch data from both URLs concurrently
Promise.all([fetch(url1), fetch(url2)])
.then(([response1, response2]) => {
// Check for errors in each response individually
if (!response1.ok || !response2.ok) {
throw new Error('One or both requests failed');
}
// Process responses in parallel using Promise.all
return Promise.all([response1.json(), response2.json()]);
})
.then(([data1, data2]) => {
// Process the parsed JSON data directly
console.log(JSON.stringify(data1));
console.log(JSON.stringify(data2));
})
.catch(error => {
console.error('Error:', error);
});
The iterable is returned as a resolved value: response array. The next Promise.all() takes another array of Promises, this time the return values of json() calls. The last then() prints the stringified JSON data.
SOP OK
protocol, domain and port match
CORS OK
a server allows it, e.g., by setting Access-Control-Allow-Origin: *
CORS NOT OK
a server disallows with its Access-Control-Allow-Origin and other headers, or by providing no CORS
In case of an error, check the reason from Developer Tools: Network traffic viewer
fetch(url, {
method: 'GET',
headers: {
'Content-Type':
'application/json'
},
mode: 'cors'
})
res.set({
// 'Access-Control-Allow-Origin': '*', //all
// 'Access-Control-Allow-Origin': 'https://m.yle.fi', //yle
'Access-Control-Allow-Origin': 'http://127.0.0.1:5500',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type'
});
no-cors only downgrades the request as "ping" replied by an opaque responseBrowser's Same-Origin Policy (SOP) and tab isolation prevent cross-site data reading and cross-tab access. But SOP cannot fully prevent successful Cross-Site Scripting (XSS) attacks. In XSS, injected malicious JavaScript impersonates a user and operates with the privileges of the trusted origin.
Key to security: prevent JS injection:
"use strict", utilize arrow functions, and embrace FP principleseval(), new Function(), and setTimeout(string)textContent over potentially dangerous innerHTML/outerHTML<script src="..." integrity="..." crossorigin="anonymous"></script>
The browser fetches the CDN script, calculates its hash, and only executes it if the calculated hash matches the integrity attribute.