1const readline = require("readline");
2
3const rl = readline.createInterface({
4 input: process.stdin,
5 output: process.stdout
6});
7
8rl.question("What is your name ? ", function saveInput(name) {
9 console.log(`His name is ${name}`);
10 rl.close();
11});
12
13rl.on("close", function saveInput() {
14 console.log("\nBYE BYE !!!");
15 process.exit(0);
16});
1/*
2 A Promise is a proxy for a value not necessarily known when the promise is created.
3 It allows you to associate handlers with an asynchronous action's eventual success
4 value or failure reason.
5*/
6let promise = new Promise((resolve , reject) => {
7 fetch("https://myAPI")
8 .then((res) => {
9 // successfully got data
10 resolve(res);
11 })
12 .catch((err) => {
13 // an error occured
14 reject(err);
15 });
16});
1function doSomething() {
2 return new Promise((resolve, reject) => {
3 console.log("It is done.");
4 // Succeed half of the time.
5 if (Math.random() > .5) {
6 resolve("SUCCESS")
7 } else {
8 reject("FAILURE")
9 }
10 })
11}
12
13const promise = doSomething();
14promise.then(successCallback, failureCallback);
1//create a Promise
2var p1 = new Promise(function(resolve, reject) {
3 resolve("Success");
4});
5
6//Execute the body of the promise which call resolve
7//So it execute then, inside then there's a throw
8//that get capture by catch
9p1.then(function(value) {
10 console.log(value); // "Success!"
11 throw "oh, no!";
12}).catch(function(e) {
13 console.log(e); // "oh, no!"
14});
15
1new Promise( (res, rej) => {
2 setTimeout(() => res(1), 1000);
3}).then( (res) => {
4 console.log(res); // 1
5 return res*2
6}).then( (res) => {
7 console.log(res); // 2
8});
9
1let doSecond = () => {
2 console.log('Do second.')
3}
4
5let doFirst = new Promise((resolve, reject) => {
6 setTimeout(() => {
7 console.log('Do first.')
8
9 resolve()
10 }, 500)
11})
12
13doFirst.then(doSecond)