[英]ES6 arrow function and setTimeOut
下面的代碼總是打印相同的隨機數,我在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); }); }
getRandom
是一個單一的無極,它創建了一個單一的一個承諾setTimeout
並解析(或拒絕)給一個(單個)的字符串。 您需要一個函數來創建一個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); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.