s1eepercat
10/3/2019 - 3:30 PM

Promises


const promise = new Promise((resolve, reject) => {
    if (true) {
        resolve('Stuff Worked');
    } else {
        reject('It Broke');
    }
})

//Error catching
promise
    .then(result => result + '!')
    .then(result2 => {
        throw Error;
        console.log(result2);
    })
    .catch((error) => console.log(error));


const promise2 = new Promise((resolve, reject) => {
    setTimeout(resolve, 100, 'Hi')
})

const promise3 = new Promise((resolve, reject) => {
    setTimeout(resolve, 1000, 'Pookie')
})

const promise4 = new Promise((resolve, reject) => {
    setTimeout(resolve, 5000, 'Is it me?')
})

//Using all promises at once
Promise.all([promise, promise2, promise3, promise4])
    .then(values => {
        console.log(values);
    })



//Real world use

const urls = [
    'http://jsonplaceholder.typicode.com/users',
    'http://jsonplaceholder.typicode.com/posts',
    'http://jsonplaceholder.typicode.com/albums'
]

Promise.all(urls.map(url => {
    return fetch(url).then(resp => resp.json())
})).then((results) => {
    console.log(results[0]);
    console.log(results[1]);
    console.log(results[2]);
}).catch(() => console.log('error'))