Promises

Testing promises https://scotch.io/tutorials/javascript-promises-for-dummies

by db_dev

HTML

Promises

JavaScript

var isMomHappy = true;

//Promise
var willIGetNewPhone = new Promise(
    function(resolve, reject) {
        if (isMomHappy) {
            var phone = {
                brand: "Google Pixel",
                color: "Rose"
            };
            resolve(phone); //fulfilled
			console.log(phone);
        } else {
            var reason = new Error("Mom is not happy.")
            reject(reason); //reject
        }
    }
);

// 2nd Promise
var showOff = function(phone) {
    /*
		//Long Way of doing the same below
	return new Promise(
        function(resolve, reject) {
            var message = 'Hey friend, I have a new ' + phone.color + ' ' + phone.brand + '!';

            resolve(message);
        }
    );*/

	// The same above but shorter!
    var message = 'Hey friend, I have a new ' + phone.color + ' ' + phone.brand + '.';
    return Promise.resolve(message);

};
// call our promise
var askMom = function() {
console.log('before asking Mom'); // Log before
    willIGetNewPhone
		.then(showOff) // chain it here
        .then(function(fulfilled) {
            //yay, you got a new phone!
            console.log(fulfilled);
            // output: Hey friend, I have a new Rose Google Pixel!
        }).catch(function(error) {
            // oops, mom didn't buy it
            console.log(error.message);
            // output: mom is not happy
        });
		console.log('after asking Mom'); // Log after
};

askMom();

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

// add two number normally
function add (num1, num2) {
	return num1 + num2
};

//const result = add(1, 2); // You will get 3 immediately


// add two numbers remotely

// get the result by calling an API
const result = getAddResultFromServer('http://www.example.com?num1=1&num2=2');
// you get result  = "undefined"



/*function getInfo(a, b) {
  return Promise.resolve(true);
}

function setInfo() {
  console.log("First");
  console.log("First");
  console.log("First");
  console.log("First");
  console.log("First");
  return...