x=21 console.log(x); let x; function fun(a) { return new Promise((resolve, reject) => { if(a>=0) { resolve("Positive"); } else { reject("Negative"); } }) } fun(10) .then((result) => console.log(result)) .catch((error) => console.log(error)) Alternative of Promises => 1) The keyword async before a function makes the function return a promise: 2) await makes a function wait for a Promise async function fun(a) { if(a>=0) { return "positive"; } else { return "negative"; } } fun(-10) .then((result) => console.log(result)) .catch((error) => console.log(error)) function fun(a) { return new Promise((resolve) => { if(a>=0) { resolve("Positive"); } }) } fun(-10) .then((result) => console.log(result)) .catch((error) => console.log(error)) var prom; async function fun(a) { prom = new Promise((resolve) => { if(a>=0) { setTimeout(function() { return resolve("Positive");},5000); } }) var out = await prom; console.log(out); } fun(10); prom.then( (result) => { console.log(result); }) #Adding Some Delay : var prom; let myPromise; prom = new Promise( function(myResolve, myReject) { let x = 0; // some code (try to change x to 5) if (x == 0) { setTimeout( function () { return myResolve("OK") }, 3000); } else { myReject("Error"); } }) function fun(a) { return new Promise((resolve, reject) => { if(a>=0) { setTimeout(() => resolve("Positive"), 3000); } else { reject("Negative"); } }) } fun(10) .then((result) => console.log(result)) .catch((error) => console.log(error)) prom.then( function(value) {console.log(value);}, function(error) {myDisplayer(error);} ############################################ { var/let/const interval = setInterval(myFunction, 1000); } (function() {clearTimeout(interval)})(); function myFunction() { let d = new Date(); document.getElementById("demo").innerHTML= d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds(); }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter