Anjil Panchal
Anjil Panchal

Reputation: 894

ES6 arrow function and setTimeOut

Below code always prints the same random number, I am using let and arrow function in the setTimeout.

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

Upvotes: 3

Views: 5652

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370819

getRandom is a single Promise, a Promise which creates a single setTimeout and resolves (or rejects) to a (single) string. 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:

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

Upvotes: 3

Related Questions