0

почему возвращается catch?

function getPost(cb){
    console.log('Получаем список постов...');
    const promise = new Promise((resolve, reject) => {
        const request = new XMLHttpRequest();
        request.open('GET', 'curr.json');
        request.onreadystatechange(() => {
            if(request.readyState === 4){
                const response = JSON.parse(request.response);
                cb(response);
                resolve();
            } else {
                reject();
            }
        })
        request.send();
    })
    return promise;
}

btn.addEventListener('click', () => {
    getPost((cb) => {
        console.log(cb);
    })
    .then(() => {console.log('Посты загружены успешно!')})
    .catch(() => {console.log('Что-то пошло не так!')})
})

1
  • readystatechange срабатывает несколько раз и не сразу со стейтом 4
    – ThisMan
    11 окт 2019 в 6:19

1 ответ 1

1
function getPost(cb){
    console.log('Получаем список постов...');
    const promise = new Promise((resolve, reject) => {
        const request = new XMLHttpRequest();
        request.open('GET', 'curr.json');
        // Используем событие onload, раз вам нужно именно окончание запроса
        request.onload(() => {
            const response = JSON.parse(request.response);
            cb(response);
            resolve();
        });
        // Обработка ошибки
        request.onerror = reject;
        request.send();
    })
    return promise;
}

Почитать:
События xmlHttpRequest

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.