简体   繁体   English

ES6箭头功能和setTimeOut

[英]ES6 arrow function and setTimeOut

Below code always prints the same random number, I am using let and arrow function in the setTimeout. 下面的代码总是打印相同的随机数,我在setTimeout中使用let和arrow函数。

 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. getRandom是一个单一的无极,它创建了一个单一的一个承诺setTimeout并解析(或拒绝)给一个(单个)的字符串。 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: 您需要一个函数来创建一个Promise,以便多次调用该函数将导致创建多个Promises(和多个随机数):

 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); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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