Skip to content

Instantly share code, notes, and snippets.

View jaydson's full-sized avatar
🏠
Working from home

Jaydson Gomes jaydson

🏠
Working from home
View GitHub Profile
fetch(URL_TO_FETCH)
.then(function(response) {
response.body.getReader().read()
.then(function(data) {
// transformando em string, para visualizarmos melhor
let fetched = String.fromCharCode.apply(null, data.value);
console.log(fetched);
});
})
.catch(function(err) {
fetch(URL_TO_FETCH)
.then(response => response.json()) // retorna uma promise
.then(result => {
console.log(result);
})
.catch(err => {
// trata se alguma das promises falhar
console.error('Failed retrieving information', err);
});
fetch(URL_TO_FETCH).then(function(response) {
response.json().then(function(data) {
console.log(data);
});
}).catch(function(err) {
console.error('Failed retrieving information', err);
});
const URL_TO_FETCH = 'https://braziljs.org/api/list/events';
fetch(URL_TO_FETCH, {
method: 'get' // opcional
})
.then(function(response) {
response.text()
.then(function(result) {
console.log(result);
})
})
const URL_TO_FETCH = 'https://braziljs.org/api/list/events';
fetch(URL_TO_FETCH, {
method: 'get' // opcional
})
.then(function(response) {
// use a resposta
})
.catch(function(err) {
console.error(err);
});
Promise.race([
new Promise((resolve, reject) => {
setTimeout(function() {
resolve('A');
}, 500);
}),
new Promise((resolve, reject) => {
setTimeout(function(){
resolve('B');
}, 300);
Promise.race([
new Promise((resolve, reject)=>{}),
new Promise((resolve, reject)=>{}),
new Promise((resolve, reject)=>{})
])
.then(result => {
console.info('Ok');
})
.catch(reason=>{
console.warn('Failed!', reason);
Promise.all([
new Promise((resolve, reject) => {}),
new Promise((resolve, reject)=>{}),
new Promise((resolve, reject)=>{})
])
.then(result => {
console.info('Ok');
})
.catch(reason => {
console.warn('Failed!', reason);
function getAddress () {
return new Promise ((resolve, reject) =>{
setTimeout(resolve, 2000); });
}
function getUser () {
return new Promise((resolve, reject) =>{
setTimeout(_=> resolve(getAddress()), 1000);
});
}
new Promise(function(resolve, reject) {
console.log('A'); // será executado reject();
// irá rejeitar a promise
console.log('B'); // será executado
throw(new Error('Falhou')); // lança uma excpetion
console.log('C'); // não será executado
});