Asynchronous programming
JavaScript runs on a single thread. It can only do one thing at a time.
Every task has to wait for the previous one to finish and this can freeze an application during slow operations (like file requests).
But JavaScript can also run code asynchronously.
Promises
Syntax:
let myPromise = new Promise(function(resolve,reject)) {
resolve(value);
reject(value);
}
Examples:
const myPromise = new Promise<number>((resolve, reject) => {
setTimeout(() => {
//! Yo quiero mi dinero!!
resolve(100);
// reject('Mi amigo se perdió');
}, 2000); // 2 segundos
});
myPromise
.then((myMoney) => {
console.log(`Tengo mi dinero ${myMoney}`);
})
.catch((reason) => {
console.warn(reason);
})
.finally(() => {
console.log('Pues a seguir con mi vida');
});
const authUserPromise = new Promise<boolean>(function(resolve, reject) {
const authUser:boolean = true;
if(authUser === true) {
resolve(true);
} else {
reject(false)
}
});
authUserPromise
.then(
() => { console.log('logged') }
)
.catch(
() => { console.log('not logged') }
);
fetch()
import type { GiphyRandomResponse } from "./data/giphy.response";
const API_KEY = 'BcK0P6s8e7LWIlpAHMOr7mCAyO7EaoXH';
const myRequest = fetch(`https://api.giphy.com/v1/stickers/random?api_key=${API_KEY}&tag=&rating=g`);
const createImageInsideDOM = (url: string) => {
const imgEl = document.createElement('img');
imgEl.src = url;
document.body.append(imgEl);
}
myRequest
.then((response) => response.json())
.then(({ data }: GiphyRandomResponse) => {
const imageUrl = data.images.original.url;
createImageInsideDOM(imageUrl);
})
.catch((err) => {
console.error(err);
});
async and await
Promise chains can become long.
async and await were created to reduce nesting and improve readability.
import type { GiphyRandomResponse } from "./data/giphy.response";
const API_KEY = 'BcK0P6s8e7LWIlpAHMOr7mCAyO7EaoXH';
const createImageInsideDOM = (url: string) => {
const imgEl = document.createElement('img');
imgEl.src = url;
document.body.append(imgEl);
}
const getRandomGifUrl = async (): Promise<string> => {
const response = await fetch(`https://api.giphy.com/v1/stickers/random?api_key=${API_KEY}&tag=&rating=g`);
const { data }: GiphyRandomResponse = await response.json();
return data.images.original.url;
}
getRandomGifUrl().then(
url => createImageInsideDOM(url)
)