ES6 箭头函数和 setTimeOut

ES6 arrow function and setTimeOut

下面的代码总是打印相同的随机数,我在 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 是一个 single 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);
}