Requirement 1: Roll a die and print out the size of the die

Idea 1: Promise’s.then() method

function fn() { return new Promise((resolve, reject) => { setTimeout(() => { let n = parseInt(Math.random() * 6 + 1, 10); resolve(n); }, 3000); }); } fn (). Then ((x) = > {the console. The log (" dice points is "+ x)}, (y) = > {the console. The log (" roll the dice failed")});Copy the code

Idea 2: Use async,await

Async is an identifier for an asynchronous function that returns an asynchronous Promise object. Await to return a function containing a Promise object. Note that await can only be used in async functions.

function fn() { return new Promise((resolve, reject) => { setTimeout(() => { let n = parseInt(Math.random() * 6 + 1, 10); resolve(n); }, 3000); }); } async function test(){//test is an asynchronous function let n=await fn() //3s after the value assigned to n console.log(n)} test()Copy the code

Requirement 2: Roll a die and guess the size of the die. Default guess large and usetry catchMethod catch error

Function fn(guess) {return new Promise((resolve, reject) => {setTimeout(() => {let n = parseInt(math.random () * 6 + 1, 10); Resolve (n); resolve(n); resolve(n); } else { reject(n); } else {if (guess === "small ") {resolve(n); } else { reject(n); }}}, 1000); }); } async function test() {try {let t = await fn(" big "); // assign the value to t console.log(" win ", t) after await 3s; } catch (error) {console.log(" guess wrong ", error); } } test();Copy the code

Need 3: Roll two dice to guess the size of the dice. Default guess mostly successful print guess (Promise. All usage)

Function fn(guess) {return new Promise(resolve, reject) => { setTimeout(() => { let n =6 //parseInt(Math.random() * 6 + 1, 10); Resolve (n); resolve(n); resolve(n); } else { reject(n); } else {if (guess === "small ") {resolve(n); } else { reject(n); }}}, 1000); }); } async function test() {try {let t = await Promise. All ([fn(' big '),fn(' big ')]); //promise.all, where t prints an array console.log(" got it ", t); } catch (error) {console.log(" guess wrong ", error); } } test();Copy the code

Requirement 4: Roll two dice to guess the size of the dice. Default guess big as long as one success print the correct guess (Promise. Race usage)

Function fn(guess) {return new Promise(resolve, reject) => { setTimeout(() => { let n =6 //parseInt(Math.random() * 6 + 1, 10); Resolve (n); resolve(n); resolve(n); } else { reject(n); } else {if (guess === "small ") {resolve(n); } else { reject(n); }}}, 1000); }); } async function test() {try {let t = await promise.race ([fn(' big '),fn(' big ')]); //promise.all, where t prints an array console.log(" got it ", t); } catch (error) {console.log(" guess wrong ", error); } } test();Copy the code