Promises - Basic Syntax

Video

JavaScript Notes

JavaScript
    // Promises - Just the Basic Facts
    // wrappers for anything async
    // ajax calls, reading files, timeouts, geolocations, 
    // talk to a database, anything that uses a callback function
    // use them to get rid of callback hell
    // fetch() returns a promise 
    
    var result = multiplyTwoNumbers(5,10)
    console.log(result); // 50

    var photo = downloadPhoto('http://localhost/cat.jpg');  // this is asynchronous
    console.log(photo)                                      // photo is likely to be 'undefined' if called immediately

    const rand = () => Math.floor(Math.random() * 10) + 1;

    // Promises - wrapper around, typically, an asynchronous function
    let p1 = new Promise((resolve, reject) => {   
        let x = 5;           // if the function runs properly, resolve will be called
        // resolve(x);       // calling resolve will call then()
        // reject(x);
        let num = rand();
        setTimeout(resolve, 1500, num)    // calls resolve function after 1.5s
    });  

    p1.then((ex) => {
        console.log(ex);
        return ex * 2;       // return statement gets passed down to the next .then() function
    }).then((x) => {
        console.log(x);
    }).catch((exx) => {      // catch() is what runs if reject is called, or if any of the '.then()' functions return an error
        console.log('caught', exx);
    })

    fetch().then().then().catch();    // the fetch function is an example of a function that returns a Promise