//add async before any function declaration to treat it as a Promise function:
async function add(x,y) {
if (typeof x !== 'number' || typeof y !== 'number') {
throw "INVALID NUMBER TYPE";
}
return x + y;
}
add(9, 4)
.then(data => {
console.log("add() function: Inside Resolve \n\nadd() function: ")
console.log(data);
})
.catch(err => {
console.log("add() function: Inside Reject")
console.log("add() function: Something Went Wrong\n\nadd() function:");
console.log(err);
})
//---------------------------------------------------------------------------------------------------
//using async-await:
async function getBitCoinPrice() {
console.log("getBitCoinPrice(): Starting the getBitCoin Function=>");
const response=await fetch('https://api.cryptonator.com/api/ticker/btc-usd');
console.log("getBitCoinPrice(): Got the Response from fetch.");
console.log("getBitCoinPrice(): Now, Parsing response for Data...");
const data = await response.json();
console.log("getBitCoinPrice(): Parsing Completed.");
console.log('getBitCoinPrice(): \nCurrent price: ');
console.log(data.ticker.price);
console.log("getBitCoinPrice Function completes, ALL DONE!!");
}
//calling getBitCoinPrice() function
getBitCoinPrice()
.then(() => {
console.log("getBitCoinPrice(): Resolved");
})
.catch(err => {
console.log("getBitCoinPrice(): AAAHHHH! ERROR\n\ngetBitCoinPrice(): ");
console.log(err);
})
// Below will be printed first because
// of the delay happening in getting the response from Promises
console.log("AFTER FUNCTION");
console.log("AFTER FUNCTION");
console.log("AFTER FUNCTION");
console.log("AFTER FUNCTION");