Задание №1. Promise
function createPromiseRandom(min, max, delay) {
return new Promise(function (resolve, reject) {
setTimeout(function(){
if(min < max){
var randNum = min + Math.random() * (max - min);
resolve(randNum);
}
else{
reject('min cant be greater than max')
}
},delay);
});
}
let p1 = createPromiseRandom(1, 100, 2000);
p1.then(function(result){
console.log(result);
});
let p2 = createPromiseRandom(1000, 100, 3000);
p2.then(function(){},function(error){
console.log(error);
});
Задание №2. Promise
new Promise(function (resolve, reject) {
debugger;
var num = prompt('Введите число');
if(!isNaN(+num)){
resolve(num);
}
else{
reject('Вы ввели нечисловое значение, повторите ввод');
}
}).catch(function (error) {
return new Promise(function (resolve, reject) {
do{
var num = prompt(error);
}
while(isNaN(+num))
resolve(num);
});
}).then(function (result) {
return new Promise(function (resolve, reject) {
console.log(result);
});
});
Задание №3. Генераторы
function* generateFibonacci() {
var fibonacciNum = 1;
var fibonacciArr = [];
yield fibonacciNum;
fibonacciArr[0] = 0;
fibonacciArr[1] = fibonacciNum;
for (var i = 2;;i++) {
fibonacciArr[i] = fibonacciArr[i - 1] + fibonacciArr[i - 2];
yield fibonacciArr[i];
}
}
let gen = generateFibonacci();
for (let i = 0; i < 10; i++) {
console.log(gen.next().value);
}
Задание №4. Генераторы
function* generateFibonacci() {
var fibonacciNum = 1;
var fibonacciArr = [];
var nextValType = yield fibonacciNum;
fibonacciArr[0] = 0;
fibonacciArr[1] = fibonacciNum;
for (var i = 2;;i++) {
var returnVal;
fibonacciArr[i] = fibonacciArr[i - 1] + fibonacciArr[i - 2];
returnVal = nextValType != 'string'? fibonacciArr[i]: fibonacciArr[i].toString();
nextValType = yield returnVal;
}
}
let gen = generateFibonacci();
console.log(gen.next().value); // 1
console.log(gen.next("string").value); // "1"
console.log(gen.next("number").value); // 2
console.log(gen.next().value); // 3
console.log(gen.next("string").value); // "5"
Weather(promises)