TIL of the Past: 20-10-10
Promise
The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
In simple words, promise is used to process async operation, and when successful it returns a single value. It is mainly used to process data received from a different source and display on the page.
Before promise, async operations were processed with a chain of callback functions, which, in complex cases, made the code very hard to read. Using promise, then and the functions that follows, this becomes way easier.
const promise = new Promise((resolve, reject) => {
if(true) {
resolve('success')
} else {
reject('failed')
Promise can either be resolved or rejected.
const urls = [
'https://swapi.dev/api/people/1/',
'https://swapi.dev/api/starships/9/',
'https://swapi.dev/api/vehicles/4/'
]
Promise.all(urls.map(url =>
fetch(url).then(response => response.json())
))
.then(results => {
results.forEach(result => {
console.log(result)
})
})
.catch(() => console.log('Oops, Something went wrong'))
By using .then
, it is possible to process chain reactions, meaning if the promise is resolved, the function after .then
is run. And .catch lets us catch any of the errors that happen in the process, no matter where, and can designate action when that catch happens.
fetch("https://jsonplaceholder.typicode.com/users/")
.then((response) => response.json())
.then(console.log);
const fetchUrl = async () => {
const response = await fetch("https://jsonplaceholder.typicode.com/users/");
const data = await response.json();
await console.log(data)
}
Using new syntax provided by ES9, it is possible to write async operation like synchronous operation. With the syntax async
, a async function is created. In this function, await
is used to pause the processing of codes until the previous promise is resolved. The very first code with await is processed synchronously and the rest is asynchronous
const urls = [
"https://jsonplaceholder.typicode.com/users",
"https://jsonplaceholder.typicode.com/posts",
"https://jsonplaceholder.typicode.com/albums",
];
const getData = async function () {
try {
const [users, posts, albums] = await Promise.all(
urls.map(async (url) => {
const response = await fetch(url);
return response.json();
})
);
console.log("users", users);
console.log("posts", posts);
console.log("albums", albums);
} catch (err) {
console.log('oops', err)
}
};
In order to make sure the function catches error, even with the new syntax, catch is used. In this new syntax, try-catch statement. With the catch written like above, when anything in the async process fails, and returns error, the catch statement will catch this error and react as desired.