const Promise = new Promise((resolve,reject) => {....});
let Promise = new Promise((resolve, reject)=>{ let a = 3; if(a==3){ resolve('Success'); } else{ reject('Failed'); } }) Promise.then((message)=>{ console.log("It is then block. The message is: ?+ message) }).catch((message)=>{ console.log("It is catch block. The message is: ?+ message) })
It is then block. The message is: Success
let success = (a) => { console.log(a + " it worked!") } let error = (a) => { console.log(a + " it failed!") } const Promise = num => { return new Promise((resolve,reject) => { if((num%2)==0){ resolve("Success!") } reject("Failure!") }) } Promise(100).then(success, error) Promise(21).then(success,error)
Success! it worked! Failure! it failed!
const Promise = num => { return new Promise((resolve,reject) => { if(num > 0){ resolve("Success!") } reject("Failure!") }) } Promise(20).then(res => { throw new Error(); console.log(res + " success!") }).catch(error => { console.log(error + " oh no, it failed!") })
Error oh no, it failed!
Promise.resolve('Success').then(function(val) { console.log(val); }, function(val) { });
function resolved(result) { console.log('Resolved'); } function rejected(result) { console.error(result); } Promise.reject(new Error('fail')).then(resolved, rejected);
Error: fail
const PromiseA = Promise.resolve('Hello'); const PromiseB = 'World'; const PromiseC = new Promise(function(resolve, reject) { setTimeout(resolve, 100, 1000); }); Promise.all([PromiseA, PromiseB, PromiseC]).then(function(values) { console.log(values); });
[ 'Hello', 'World', 1000 ]
const Promise1 = new Promise((resolve,reject) => { setTimeout(resolve("Promise 1 is first"),1000) }) const Promise2= new Promise((resolve,reject) =>{ setTimeout(resolve("Promise 2 is first"),2000) }) Promise.race([Promise1,Promise2]).then(result => { console.log(result); })
Promise 1 is first
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <script> const PromiseA = () =>{ return new Promise((resolve,reject)=>{ resolve("Hello Promoise A"); }); } const PromiseB = () =>{ return new Promise((resolve,reject)=>{ resolve("Hello Promise B"); }); } const PromiseC = () =>{ return new Promise((resolve,reject)=>{ resolve("Hello Promise C"); }); } PromiseA().then((A)=>{ console.log(A); return PromiseB(); }).then((B)=>{ console.log(B); return PromiseC(); }).then((C)=>{ console.log(C); }); </script> </body> </html>