ES6箭头功能和setTimeOut

时间:2019-05-05 05:44:07

标签: javascript arrow-functions

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

1 个答案:

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