Skip to main content

JavaScript
What Are Promises and How to Use Them

script.js

// AZUL CODING ---------------------------------------
// JavaScript - What Are Promises and How to Use Them
// https://youtu.be/OFDKQh1FbyU


// Part 1

var promise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve("done") // or reject("error")
    }, 5000);
});


// Part 2

new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve("done"); // or reject("error")
    }, 1000);

}).then((result) => {
    console.log(result);

}).catch((err) => {
    console.log(err);
});

new Promise(resolve => {
    setTimeout(() => resolve(1), 1000);

}).then((result) => {
    console.log(result);
    return new Promise(resolve => {
        setTimeout(() => resolve(2), 1000);
    });

}).then((result) => {
    console.log(result);
});


// Part 3

function delay(secs) {
    return new Promise(resolve => 
        setTimeout(() => resolve(secs), secs * 1000));
}

function delayError(secs) {
    return new Promise((resolve, reject) => 
        setTimeout(() => reject(new Error(`Failed after ${secs} secs`)), secs * 1000));
}

Promise.all([
    delay(1), delay(2), delay(3)
]).then(console.log);

Promise.any([
    delayError(1), delay(2), delay(3)
]).then(console.log);

Promise.allSettled([
    delay(1), delayError(2), delayError(3)
]).then(console.log).catch(console.log);


// Part 4

let images = [
    "https://jsonplaceholder.typicode.com/photos/1",
    "https://jsonplaceholder.typicode.com/photos/2",
    "https://jsonplaceholder"
];

function addImage(resp) {
    resp.json().then(json => {
        let el = document.createElement("img");
        el.src = json.thumbnailUrl;
        document.body.appendChild(el);
    });
}

Promise.allSettled(images.map(url => fetch(url)))
    .then(results => {
        results.forEach(result => {
            if (result.status == "fulfilled") {
                console.log(result.value);
                addImage(result.value);

            } else if (result.status == "rejected") {
                console.log(result.reason);
            }
        });
    });

Enjoying this tutorial?