"bracket-pair-colorizer-2.colors": [
"#fafafa",
"#9F51B6",
"#F7C244",
"#F07850",
"#9CDD29",
"#C497D4"
],
-
-
Save ismaeldevmw/a6315798351a971d92ded7d22b94746e to your computer and use it in GitHub Desktop.
/** | |
* Script para agregar una clase al menu una vez se haga scroll para que deje de ser transparente | |
*/ | |
const myNav = document.querySelector('.Navigation'); | |
window.onscroll = function () { | |
if (window.scrollY > 100) { | |
myNav.classList.add('scrolled'); | |
} else { | |
myNav.classList.remove('scrolled'); | |
} | |
}; |
$(document).ready(function () { | |
$('a[href^="#"]').on('click', function (e) { | |
e.preventDefault(); | |
let target = this.hash, | |
$target = $(target); | |
$('html, body').stop().animate({ | |
'scrollTop': $target.offset().top | |
}, 900, 'swing', function () { | |
window.location.hash = target; | |
}); | |
}); | |
}); |
$(function () { | |
$('[data-toggle="tooltip"]').tooltip({ | |
template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>' | |
}) | |
$(document).on('click', '.update-btn', function() { | |
const $this = $(this); | |
const marcaID = $this.attr('data-marcaid'); | |
const marcaNombre =$this.attr('data-nombre'); | |
$('#input-nombre').val(marcaNombre); | |
$('#input-marcaid').val(marcaID); | |
}); | |
$(document).on('submit', '#modal-form', function(e) { | |
e.preventDefault(); | |
const $updatedNombre = $('#input-nombre').val(); | |
const $marcaID = $('#input-marcaid').val(); | |
const payload = { | |
nombre: $updatedNombre | |
}; | |
$.ajax({ | |
type: 'PUT', | |
url: `/marcas/update/${$marcaID}`, | |
data: payload | |
}) | |
.done((data) => { | |
location.reload(); | |
$('#myModal').modal('toggle'); | |
console.log(data); | |
if (data.status == 'success') { | |
toastr.success(data.message); | |
} | |
}) | |
.fail((err) => { | |
console.log(err); | |
if (err.responseJSON.status == 'validationErrors') { | |
toastr.error(err.responseJSON.message); | |
} | |
}); | |
}); | |
$(document).on('click', '.delete-btn', function() { | |
const answer = confirm('¿Estás seguro?'); | |
if (answer) { | |
const $this = $(this); | |
const marcaID = $this.attr('data-marcaid'); | |
$.ajax({ | |
type: 'DELETE', | |
url: `/marcas/delete/${marcaID}` | |
}) | |
.done((data) => { | |
location.reload(); | |
console.log(data); | |
if (data.status == 'success') { | |
toastr.success(data.message); | |
} | |
}) | |
.fail((err) => { | |
console.log(err); | |
if(err.responseJSON.status == 'error'){ | |
toastr.error(err.responseJSON.message); | |
} | |
}); | |
} | |
}); | |
}); | |
new Vue({ | |
el: '#crud', | |
created: function() { | |
this.getMarcas(); | |
}, | |
data: { | |
marcas: null, | |
showBorrar: null, | |
nuevamarca: { | |
nombre: '' | |
}, | |
marca: { | |
marcaid: '', | |
nombre: '' | |
} | |
}, | |
methods: { | |
getMarcas: function() { | |
var urlMarcas = 'marcas/get'; | |
axios.get(urlMarcas).then((response) => { | |
this.marcas = response.data.data | |
}) | |
.catch((error) => { | |
console.log(error); | |
}); | |
}, | |
deleteMarca: function(id) { | |
const answer = confirm('¿Estás seguro?'); | |
if (answer) { | |
var url = '/marcas/delete/' + id; | |
axios.delete(url).then((response) => { | |
this.getMarcas(); | |
toastr.success(response.data.message); | |
console.log(response); | |
}) | |
.catch((error) => { | |
console.log(error); | |
}); | |
} | |
}, | |
editMarca: function(id) { | |
var url = '/marcas/edit/' + id; | |
axios.get(url).then((response) => { | |
this.marca = response.data.data[0]; | |
console.log(this.marca); | |
}) | |
.catch((error) => { | |
console.log(error); | |
}); | |
}, | |
updateMarca: function() { | |
var id = this.marca.marcaid; | |
var url = '/marcas/update/' + id; | |
var params = this.marca; | |
axios.put(url, params).then((response) => { | |
if (response.data.status == 'success') { | |
toastr.success(response.data.message); | |
this.getMarcas(); | |
$('#editModal').modal('toggle'); | |
console.log(response) | |
} else { | |
toastr.info(response.data.message); | |
} | |
}) | |
.catch((error) => { | |
console.log(error); | |
}) | |
}, | |
createMarca: function() { | |
var url = '/marcas/create'; | |
}, | |
borrarMarca: function(id) { | |
this.showBorrar = id; | |
}, | |
cancelarBorrado: function() { | |
this.showBorrar = null; | |
}, | |
confirmarBorrado: function(id) { | |
const answer = confirm('¿Estás seguro?'); | |
if (answer) { | |
var url = '/marcas/delete/' + id; | |
axios.delete(url).then((response) => { | |
this.showBorrar = null; | |
this.getMarcas(); | |
toastr.success(response.data.message); | |
console.log(response); | |
}) | |
.catch((error) => { | |
this.showBorrar = null; | |
toastr.error(error.response.data.message); | |
console.log(error); | |
}); | |
} else { | |
this.showBorrar = null; | |
} | |
} | |
} | |
}); |
let bobsFollowers = ['Joe', 'Marta', 'Sam', 'Erin']; | |
let tinasFollowers = ['Sam', 'Marta', 'Elle']; | |
let mutualFollowers = []; | |
for (let i = 0; i < bobsFollowers.length; i++) { | |
for (let j = 0; j < tinasFollowers.length; j++) { | |
if (bobsFollowers[i] === tinasFollowers[j]) { | |
console.log(bobsFollowers[i]) | |
mutualFollowers.push(bobsFollowers[i]); | |
} | |
} | |
}; |
Dentro de JavaScript han habido varias formas de hacer asincronismo, a lo largo de la historia del lenguaje se han ido añadiendo nuevas cara´cterísticas que han resuelto proplemas de legibilidad y sobre todo flexibilidad a la hora de implementarlo y es aquí donde vemos dintintos ejemplos de como implementarlo en sus distintas formas.
- Clona el repositorio en tu máquina
https://github.com/ismaeldevmw/asincronismo
Instala los librerías con npm o yarn
$ npm install
$ yarn install
Ejecuta los scripts
$ npm run callback
$ npm run callback:challenge
$ npm run promise
$ npm run promise:challenge
$ npm run async
$npm run async:challenge
Una función de devolución de llamada es una función que se pasa a otra función como argumento, que luego se invoca dentro de la función externa para completar algún tipo de rutina o acción.
function sum(num1, num2) {
return num1 + num2
}
function calc(num1, num2, callback) {
return callback(num1, num2)
}
console.log(calc(6, 2, sum))
function date(callback) {
console.log(new Date)
setTimeout(function () {
let date = new Date
callback(date)
}, 3000)
}
function printDate(dateNow) {
console.log(dateNow)
}
date(printDate)
let XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
let API = 'https://rickandmortyapi.com/api/character/';
function fetchData(url_api, callback) {
let xhttp = new XMLHttpRequest();
xhttp.open('GET', url_api, true);
xhttp.onreadystatechange = function (event) {
if(xhttp.readyState === 4) {
if (xhttp.status === 200) {
callback(null, JSON.parse(xhttp.responseText))
} else {
const error = new Error('Error ' + url_api)
return callback(error, null)
}
}
}
xhttp.send();
}
fetchData(API, function (error1, data1) {
if (error1) console.log(error1);
fetchData(API + data1.results[0].id, function (error2, data2) {
if (error2) console.log(error2)
fetchData(data2.origin.url, function (error3, data3) {
if (error3) console.log(error3);
console.log(data1.info.count);
console.log(data2.name);
console.log(data3.dimension);
});
});
});
El objeto Promise representa la finalización (o falla) eventual de una operación asincrónica y su valor resultante.
const somethingWillHappen = () => {
return new Promise((resolve, reject) => {
if (true) {
resolve('Hey!');
} else {
reject('Whoops!');
}
});
};
somethingWillHappen()
.then(response => console.log(response))
.catch(err => console.log(err));
const somethingWillHappen2 = () => {
return new Promise((resolve, reject) => {
if(true) {
setTimeout(() => {
resolve('True');
}, 2000)
} else {
const error = new Error('Whoop!');
reject(error);
}
});
}
somethingWillHappen2()
.then(response => console.log(response))
.catch(err => console.log(err))
Promise.all([somethingWillHappen(), somethingWillHappen2()])
.then(response => {
console.log('Array of results', response);
})
.catch(err => {
console.log(err);
});
const fetchData = require('../utlils/fetchData');
const API = 'https://rickandmortyapi.com/api/character/';
fetchData(API)
.then(data => {
console.log(data.info.count);
return fetchData(`${API}${data.results[0].id}`)
})
.then(data => {
console.log(data.name);
return fetchData(data.origin.url)
})
.then(data => {
console.log(data.dimension);
})
.catch(err => console.log(err))
Una función asincrónica es una función declarada con la palabra clave asincrónica. Las funciones asíncronas son instancias del constructor AsyncFunction, y la palabra clave de espera está permitida dentro de ellas. Las palabras clave asíncrona y en espera permiten que el comportamiento asíncrono basado en promesas se escriba en un estilo más limpio, evitando la necesidad de configurar explícitamente las cadenas de promesas.
const doSomethingAsync = () => {
return new Promise((resolve, reject) => {
(true)
? setTimeout(() => resolve('Do something'), 3000)
: reject(new Error('Test Error'))
});
}
const doSomething = async () => {
const something = await doSomethingAsync();
console.log(something);
}
console.log('Before 1');
doSomething();
console.log('After 1');
const anotherFunction = async () => {
try {
const something = await doSomethingAsync();
console.log(something);
} catch(error) {
console.log(error);
}
}
console.log('Before 2');
anotherFunction();
console.log('After 2');
const fetchData = require('../utlils/fetchData');
const API = 'https://rickandmortyapi.com/api/character/';
const anotherFunction = async (url_api) => {
try {
const data = await fetchData(url_api);
console.log(data.info.count);
const character = await fetchData(`${url_api}${data.results[0].id}`);
console.log(character.name);
const origin = await fetchData(character.origin.url);
console.log(origin.dimension);
} catch(error) {
console.log(error);
}
}
console.log('Before');
anotherFunction(API);
console.log('After');
const DATE_UNITS = {
day: 86400,
hour: 3600,
minute: 60,
second: 1
}
const getSecondsDiff = timestamp => (Date.now() - timestamp) / 1000
// Una function que recibe los segundos que han pasado y determina qué unidad de medida necesita para representar mejor el tiempo
const getUnitAndValueDate = (secondsElapsed) => {
const entries = Object.entries(DATE_UNITS)
for (const [unit, secondsInUnits] of entries) {
const match = secondsElapsed >= secondsInUnits || unit === 'second'
if(match) {
const value = Math.floor(secondsElapsed / secondsInUnits) * -1
return {value, unit}
}
}
}
// Finalmente, la function principal. Le pasamos el timestamp y el idioma que queremos. ¡Y ya está!
const timeAgo = (timestamp, locale) => {
const rft = new Intl.RelativeTimeFormat(locale)
const secondsElapsed = getSecondsDiff(timestamp)
const {value, unit} = getUnitAndValueDate(secondsElapsed)
return rtf.format(value, unit)
}
timeAgo(1643728081400) // --> hace 2 minutos
timeAgo(1643728081400, 'en') // --> 2 minutes ago