Показать сообщение отдельно
  #11 (permalink)  
Старый 28.10.2023, 11:03
Профессор
Отправить личное сообщение для Rise Посмотреть профиль Найти все сообщения от Rise
 
Регистрация: 07.11.2013
Сообщений: 4,662

Сообщение от voraa
С промисом
А без промиса $.ajax не будет работать?

Еще с версии 1.8 .then() работает, а .catch() с версии 3. Хотя у них там свои промисы - Deferred, но с версии 3 они их сделали совместимыми с ES2015 Promises. Вроде работает...

then/catch:
function getJson(url) {
    return $.getJSON(url);
}

let promise = getJson('https://jsonplaceholder.typicode.com/posts');
//  promise = getJson('https://error.jsonplaceholder.typicode.com/posts');

promise
    .then(data => {
        console.log('then', data);
    })
    .catch(error => {
        console.log('catch', error.statusText);
    });

async/await:
function getJson(url) {
    return $.getJSON(url);
}

(async () => {
    try {
        let data = await getJson('https://jsonplaceholder.typicode.com/posts');
        //  data = await getJson('https://error.jsonplaceholder.typicode.com/posts');
        console.log('then', data);
    } catch (error) {
        console.log('catch', error.statusText);
    }
    console.log('next');
})();
Ответить с цитированием