Demo 1
Create new Javascript file named demo1.js. This file contains code demo as below:
var p = new Promise((resolve, reject) => resolve(5));
p.then((val) => console.log('Value: ' + val));
Run Demo 1
Use node demo1.js statement run code demo
Value: 5
Demo 2
Create new Javascript file named demo2.js. This file contains code demo as below:
const isSmallThenTen = (num) => {
return new Promise((resolve, reject) => {
if (num < 10) {
resolve(true)
} else {
reject(false)
}
})
};
isSmallThenTen(91)
.then(res => console.log('The number is smaller then 10'))
.catch(err => console.log('The number is greater than 10'));
isSmallThenTen(5)
.then(res => console.log('The number is smaller then 10'))
.catch(err => console.log('The number is greater than 10'));
Run Demo 2
Use node demo2.js statement run code demo
The number is smaller then 10
The number is greater than 10
Demo 3
Create new Javascript file named demo3.js. This file contains code demo as below:
const timeoutIn = (time) => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(time), time)
})
}
timeoutIn(2000).then(res => console.log(`Resloved in ${res/1000} seconds`))
Run Demo 3
Use node demo3.js statement run code demo
Resloved in 2 seconds
Demo 4
Create new Javascript file named demo4.js. This file contains code demo as below:
var p1 = new Promise((resolve, reject) => {
if (true)
throw new Error("rejected!");
else
resolve(4);
});
p1.then((val) => val + 2)
.then((val) => console.log("got ", val))
.catch((err) => console.log("error: ", err.message));
var p2 = new Promise((resolve, reject) => {
resolve(4);
});
p2.then((val) => val + 2)
.then((val) => { throw new Error("step 2 failed!") })
.then((val) => console.log("got ", val))
.catch((err) => console.log("error: ", err.message));
Run Demo 4
Use node demo4.js statement run code demo
error: rejected!
error: step 2 failed!