下面的代码总是打印相同的随机数,我在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);
});
}
答案 0 :(得分:3)
getRandom
是一个 single Promise,它创建一个setTimeout
并将其解析(或拒绝)为(单个)字符串的Promise。您需要一个 function 来创建一个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);
}