简体   繁体   中英

ES6 arrow function and setTimeOut

Below code always prints the same random number, I am using let and arrow function in the setTimeout.

 let getRandom = new Promise((resolve, reject) => { setTimeout( () => { let random = parseFloat(Math.random() * 30); if(random > 20) { resolve(`Yes!! ${random} is our random number`); } else { reject(`Oh no!! ${random} is not our random number`); } }, parseInt(Math.random()*1000)); }); for(let counter = 0; counter < 10; counter++) { getRandom.then( response => { console.log(response); }, error => { console.log(error); }); } 

getRandom is a single Promise, a Promise which creates a single setTimeout and resolves (or rejects) to a (single) string. You want a function which creates a Promise instead, so that calling that function multiple times will result in multiple Promises (and multiple random numbers) being created:

 const getRandom = () => new Promise((resolve, reject) => { setTimeout(() => { const random = Math.random() * 30; if (random > 20) { resolve(`Yes!! ${random} is our random number`); } else { reject(`Oh no!! ${random} is not our random number`); } }, Math.random() * 1000); }); for (let counter = 0; counter < 10; counter++) { getRandom() .then(console.log) .catch(console.log); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM