js promise. Последовательная проверка на наличие элементов через промисы
Нужно что бы проверка шла вначале на hello, если hello появилось пошла проверка на World, если на World прошла идет проверка на Button.Почему у меня всё сразу проверяется ?
const hello = '<p id="idHello">hello</p>'
const world = '<p id="idWorld">world</p>'
const button = '<button id="idButton" onclick="showanything()"> BUTTON </button>'
let showanything = function showanything() {
alert('Вы нажали на кнопку');
}
setTimeout(() => {
document.write(hello);
}, 2000);
setTimeout(() => {
document.write(world);
}, 4000);
setTimeout(() => {
document.write(button);
}, 6000);
let timerFunc = function(element_id) {
let timerId = setInterval(() => {
if (document.getElementById(element_id)) {
console.log(`${element_id} exist`);
clearInterval(timerId);
clearTimeout(stopTimer);
return element_id
} else {
console.log(`${element_id} does not exist`);
}
}, 1000)
let stopTimer = setTimeout(() => {
clearInterval(timerId);
console.log('timeout');
}, 10000);
}
var request1 = timerFunc('idHello');
var request2 = timerFunc('idWorld');
Promise.all([request1, request2]).then(function() {
console.log('da')
});
Ответы (1 шт):
Автор решения: Grundy
→ Ссылка
Promise.all переходит в состояние resolved, когда все Promise, переданные в аргументах, перешли в состояние resolved.
В данном случае передается массив состоящий из undefined, как следствие, Promise.all разрешается сразу.
Для решения достаточно, чтобы timerFunc возвращал Promise, например так
let timerFunc = function(element_id) {
return new Promise(r => {
let timerId = setInterval(() => {
if (document.getElementById(element_id)) {
console.log(`${element_id} exist`);
clearInterval(timerId);
clearTimeout(stopTimer);
r(element_id)
} else {
console.log(`${element_id} does not exist`);
}
}, 1000)
let stopTimer = setTimeout(() => {
clearInterval(timerId);
console.log('timeout');
r('timeout');
}, 10000);
});
}
const hello = '<p id="idHello">hello</p>'
const world = '<p id="idWorld">world</p>'
const button = '<button id="idButton" onclick="showanything()"> BUTTON </button>'
let showanything = function showanything() {
alert('Вы нажали на кнопку');
}
setTimeout(() => {
document.write(hello);
}, 2000);
setTimeout(() => {
document.write(world);
}, 4000);
setTimeout(() => {
document.write(button);
}, 6000);
let timerFunc = function(element_id) {
return new Promise(r => {
let timerId = setInterval(() => {
if (document.getElementById(element_id)) {
console.log(`${element_id} exist`);
clearInterval(timerId);
clearTimeout(stopTimer);
r(element_id)
} else {
console.log(`${element_id} does not exist`);
}
}, 1000)
let stopTimer = setTimeout(() => {
clearInterval(timerId);
console.log('timeout');
r('timeout');
}, 10000);
});
}
var request1 = timerFunc('idHello');
var request2 = timerFunc('idWorld');
Promise.all([request1, request2]).then(function() {
console.log('da')
});