Select Page
JavaScript ES6+ : Promises
Jayman Pandya
May 12, 2020

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 ✌️

Let's Talk

If you liked what you have seen, then let’s connect and make something amazing together.

Email me at converse@jaymanpandya.com or send a DM on my twitter @jaymanpandya