Promise
Concept
Reference: MDN
Promise states:
- pending
- fulfilled
- rejected
Example
const condition = true;
const p = new Promise((resolve, reject) => {
if (condition) resolve('Valid promise');
else reject('Invalid promise');
});
p.then(r => console.log(r));
//=> Valid promise
Handling Errors
const condition = true;
const promise = new Promise((resolve, reject) => {
if (condition) resolve('Valid promise');
else reject('Invalid promise');
});
promise.then(r => console.log(r)).catch(r => console.log(r));
//=> Valid promise
const condition = false;
const promise = new Promise((resolve, reject) => {
if (condition) resolve('Valid promise');
else reject('Invalid promise');
});
promise.then(r => console.log(r)).catch(r => console.log(r));
//=> Invalid promise
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function rand(end) {
const promise = new Promise((resolve, reject) => {
if (end > 0) resolve(getRandomIntInclusive(0, end));
else reject('Invalid number');
});
return promise;
}
rand(10)
.then(rand => console.log(rand))
.catch(error => console.log(error));
//=> 9
rand('a')
.then(rand => console.log(rand))
.catch(error => console.log(error));
//=> Invalid number
Chaining Promises
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function rand(end) {
const promise = new Promise((resolve, reject) => {
if (end > 0) resolve(getRandomIntInclusive(0, end));
else reject('Invalid number');
});
return promise;
}
async function sumAsync(a, b) {
return a + b;
}
rand(10)
.then(rand => sumAsync(1, rand))
.then(sum => console.log(sum));
//=> 2
Demo
function getJSON(url) {
const promise = new Promise((resolve, reject) => {
const request = new XMLHttpRequest();
request.open('GET', url);
request.onload = () => {
if (request.status === 200) {
resolve(request.response);
} else {
reject(Error(request.statusText));
}
};
request.onerror = () => {
reject(Error('Error fetching data.'));
};
request.send();
});
return promise;
}
const cepURL = 'https://viacep.com.br/ws/01001000/json/';
getJSON(cepURL)
.then(res => JSON.parse(res))
.then(json => console.log(json));
//=> {
// cep: "01001-000",
// logradouro: "Praça da Sé",
// complemento: "lado ímpar",
// bairro: "Sé",
// localidade: "São Paulo",
// uf: "SP",
// unidade: "",
// ibge: "3550308",
// gia: "1004"
//}