gpt4 book ai didi

javascript - ES6 箭头函数和 setTimeOut

转载 作者:行者123 更新时间:2023-11-29 18:42:29 27 4
gpt4 key购买 nike

下面的代码总是打印相同的随机数,我在 setTimeout 中使用了 let 和箭头函数。

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

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

关于javascript - ES6 箭头函数和 setTimeOut,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55989168/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com