03 - Promise


// Example 1 on how to use Promise (with a variable):
//====================================================
console.log("START Example 1 Output");

let x = new Promise(function (resolve, reject) {

    setTimeout(function () {
        let randomNumber = Math.random(); // generates a decimal value between 0 and 1
        console.log('from Example 1:');
        console.log(randomNumber);
        if (randomNumber < 0.5) {
            resolve();
        } else {
            reject();
        }
    }, 2000);
})

x.then(function () {
    console.log("Example 1 Resolved");
})
.catch(function () {
    console.log("Example 1 Rejected");
})

console.log("Example 1 ENDS");


// -------------------------------------------------------------------------------


// Example 2 on how to use Promise (with a function):
//====================================================
function fun() {
    
    return new Promise(function (resolve, reject) {

        setTimeout(function () {
            let randomNumber = Math.random();
            console.log('From Example 2: ');
            console.log(randomNumber);
            if (randomNumber < 0.5) {
                resolve();
            } else {
                reject();
            }
        }, 2000);
    })

}

fun().then(function () {
    console.log("Promise from Example 2 Resolved")
})
.catch(function () {
        console.log("Promise from Example 2 Rejected");
})