Published
Edited
Nov 22, 2021
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
{
function sun() {
var x = Math.floor(Math.random() * (4 - 1 + 1)) + 1;
return x;
}

function mult(func) {
var x = 5 + func();
return x;
}

return mult(sun);
}
Insert cell
Insert cell
function greet(name, callback) {
console.log('Hi' + ' ' + name);
callback();
}
Insert cell
// callback function
function callMe() {
console.log('Callback!');
}
Insert cell
Insert cell
Insert cell
setTimeout(callMe, 1000)
Insert cell
Insert cell
Insert cell
{ //Пример со вложенными запросами к бд вместо join-a:
const q1 = "SELECT * FROM users WHERE id = 1;";
client.query(q1, (res1) => {
const user = res1.rows[0];
const q2 = `SELECT * FROM purchases WHERE id = ${user.purchases[0].id};`;
client.query(q2, (res2) => {
const purchase = res2.rows[0];
const q3 = `SELECT * FROM products WHERE id = ${purchase.products[0].id};`;
client.query(q3, (res3) => {
const product = res3.rows[0];
// и т.д.
})
})
});
}
Insert cell
Insert cell
Insert cell
{
let promise = new Promise(function(resolve, reject) {
// через 1 секунду сигнализировать, что задача выполнена с результатом "done"
setTimeout(() => resolve("done"), 1000);
})
let promiseReject = new Promise(function(resolve, reject) {
// спустя одну секунду будет сообщено, что задача выполнена с ошибкой
setTimeout(() => reject(new Error("Whoops!")), 1000);
});
}
Insert cell
Insert cell
{
let promise = Promise.resolve();
promise.then(() => alert("Промис выполнен"));
alert("Код выполнен");
}
Insert cell
Insert cell
Promise.resolve()
.then(() => "Промис выполнен")
.then(() => Promise.resolve("Код выполнен"))
Insert cell
Insert cell
{
new Promise(function(resolve, reject) {
setTimeout(() => resolve(1), 1000); // (*)
}).then(function(result) { // (**)
alert(result); // 1
return result * 2;

}).then(function(result) { // (***)
alert(result); // 2
return result * 2;
}).then(function(result) {
alert(result); // 4
return result * 2;
});
}
Insert cell
Insert cell
Insert cell
Insert cell
{
Promise.all([
new Promise(resolve => setTimeout(() => resolve(1), 3000)), // 1
new Promise(resolve => setTimeout(() => resolve(2), 2000)), // 2
new Promise(resolve => setTimeout(() => resolve(3), 1000)) // 3
]).then(alert); // когда все промисы выполнятся, результат будет 1,2,3
// каждый промис даёт элемент массива
}
Insert cell
Insert cell
{
const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo'));
const promises = [promise1, promise2];
Promise.allSettled(promises).
then((results) => results.forEach((result) => console.log(result.status)));
// expected output:
// "fulfilled"
// "rejected"
}
Insert cell
Insert cell
Promise.race([
new Promise((resolve, reject) => setTimeout(() => resolve(3), 1000)),
new Promise((resolve, reject) => setTimeout(() => reject(new Error("Ошибка!")), 2000)),
new Promise((resolve, reject) => setTimeout(() => resolve(1), 1000))
]).then(alert); // 1. Быстрее всех выполнится последний промис.
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
{
async function f() {
return 1;
}
f().then(alert); // 1
}
Insert cell
Insert cell
async function f() {
let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("готово!"), 1000)
});
let result = await promise; // будет ждать, пока промис не выполнится (*)
alert(result); // "готово!"
}
return f();
Insert cell
Insert cell
{
const getFirstUserData = async () => {
try {
const response = await fetch("/users.json"); // get users list
const users = await response.json(); // parse JSON
const user = users[0]; // pick first user
const userResponse = await fetch(`/users/${user.name}`); // get user data
const userData = await userResponse.json(); // parse JSON
return userData;
} catch (err) {
console.error("Something went wrong", err);
}
};
getFirstUserData();
}
Insert cell
Insert cell
{
const err = {};
const getFirstUserData = async () => {
const response = await fetch('/users.json'); // get users list
const users = await response.json(); // parse JSON
const user = users[0] // pick first user
const userResponse = await fetch(`/users/${user.name}`); // get user data
const userData = await userResponse.json(); // parse JSON
return userData;
};
getFirstUserData().catch(err)
{
console.error('Something went wrong');
console.error(err);
};
}
Insert cell
Insert cell
Insert cell
Insert cell
function vanillaJS() {
var count = 0;
var button = document.querySelector('button');
button.addEventListener('click', () => console.log(`Clicked ${++count} times`));
}
Insert cell
function RxJS() {
var button = document.querySelector('button');
rxjs.fromEvent(button, 'click').pipe(
rxjs.operators.scan(count => count + 1, 0)
).subscribe(count => console.log(`Clicked ${count} times`));
}
Insert cell
Insert cell
{
const {
operators: { map, filter },
Observable: { of }
} = Rx;
//тут должны быть import'ы, чтобы map работал корректно

of(1, 2, 3)
.pipe(
// пропускаем только нечетные значения
filter((value) => value % 2 !== 0),
map((value) => value * 2) //умножаем каждое число на два
)
.subscribe({
next: console.log // Выведет 2, 6
});
}
Insert cell
Rx = require("https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.6.0-forward-compat.5/Rx.min.js")
Insert cell
Rx.Observable
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more