JavaScript ES6+ : Promises

Follow me on twitter @jaymanpandya

Promises are object that will produce some data in future or will return an error why the promised data was not produced. then() callback function is used to intimate when the resolved data is returned. catch() is chained to then() to check for any errors that must have occured while retrieving the promised data.

const postData = fetch('http://data.ratp.fr/api/datasets/1.0/search/?q=le-mans');

postData
    .then(data => data.json())
    .then(data => { console.log(data) })
    .catch(err => { 
        console.log(err);
    });

You can write your own Promises.

const customPromise = new Promise ((resolve, reject) => {
    resolve(fetch('http://data.ratp.fr/api/datasets/1.0/search/?q=le-mans'));
    reject('There was an error getting a response from the API');
});

customPromise
    .then(data => data.json())
    .then(data => { console.log(data) })
    .catch(err => { 
        console.log(err);
    });

You can also chain promises and control the flow

const clubs = [
    {title: 'Club Onyx', accessTo: 'members', id: 1},
    {title: 'Club Emerald', accessTo: 'all', id: 2},
    {title: 'Club Pogo', accessTo: 'children', id: 3}
]

const audience = [
    {type: 'members', description: 'People who own the house or have rented it in the building'},
    {type: 'all', description: 'People who own the house or have rented it in the building and their guests'},
    {type: 'children', description: 'Children of people who own the house or have rented it in the building and children of their guests'},
]

function getClubDetails(id) {
    return new Promise((resolve, reject) =>{
        setTimeout(() => {
            const club = clubs.find(club => club.id === id);
            if(club) {
                resolve(club);
            } else {
                reject(Error(`We are sorry, Club not found.`));
            }
        }, 2000);
    });
}

function hydrateClub(club) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            const audienceInfo = audience.find(demographic => demographic.type === club.accessTo);
            if(audienceInfo) {
                club.accessTo = audienceInfo;
                resolve(club);
            } else {
                reject(Error(`We are sorry, Audience not found.`));
            }
        }, 2000);
    });
}

getClubDetails(3)
    .then(club => {
        return hydrateClub(club);
    }).then(club => {
        console.log(club);
    }).catch(err => {
        console.error(err);
    });

Working with multiple promises

const parisDataset = fetch('http://data.ratp.fr/api/datasets/1.0/search/?q=paris');
const lemansDataset = fetch('http://data.ratp.fr/api/datasets/1.0/search/?q=le-mans');

Promise
    .all([parisDataset, lemansDataset])
    .then(responses => {
        return Promise.all(
            responses.map(
                response => response.json()
            )
        )
    })
    .then(responses => {
        console.log(responses);
    });

Peace ✌️

I am an UI designer with a flair for front-end development that makes any brand shine at what they do best. I am right now building amazing products for our clients both Indian and International at Interactive Digital Labs. I am part of the Design and Marketing Teams for Make WordPress and has spoken at local camps on Gutenberg as well as the importance of user experience. I am not intimidated by markup, languages, or tools: HTML to CSS, wireframing to prototyping, JavaScript to agile development, and design programs including Sketch, Adobe XD, Figma, Photoshop, Illustrator, InDesign etc. I love languages, and not just programming either. I speak English, Hindi, Marathi, and Gujarati. When I am not taking courses to improve my skills, I am trying new food, dabbling in filmmaking and photography, and running and cycling. Say hi to me on Twitter here @jaymanpandya.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.