Асинхронность в fetch
Я так понимаю что асинхронно так не отработает или я что-то делаю не так?
async function getData(url='') {
const response = await fetch(url, {
credentials: 'same-origin',
method: 'GET'
});
return await response.json();
}
console.log(1);
getData('/foo')
.then((data) => {
console.log(2);
});
console.log(3);
Никак не заставить выполнятся последовательно?
Ответы (3 шт):
Автор решения: Vadim
→ Ссылка
Я обычно так удовлетворяюсь:
const afetch=(_url)=>{
return new Promise((resolve)=>{
$.ajax({
url: _url,
type: 'GET',
data: {},
async: true,
}).done((r)=>{
if(!r)r = false;
resolve(r);
}).catch((e)=>{
console.log(e.status, e.responseText, e);
resolve(false);
});
});
};
(async()=>{
let r = await afetch('http://google.com/');
// code, any work with response
console.log('response', r);
})();
пс я знаю що можно await $.ajax, но оно работает раз через раз (не устраивает)
Автор решения: Alexander Lonberg
→ Ссылка
Последовательно такая конструкция работать не будет.
async function getData(url = '') {
const response = await fetch(url, {
credentials: 'same-origin',
method: 'GET'
});
// Нет тут никакого JSON
return await response.json();
}
console.log(1);
getData('/foo')
.then((data) => {
console.log(2);
}).catch(() => {
console.log('Error: И все тут работает');
});
console.log(3);
// Только так
void async function() {
try {
await getData('/foo')
} catch (e) {
console.log('Первое сообщение')
}
console.log('... второе')
}()
Автор решения: Alexander Zaytsev
→ Ссылка
В javascript каждый promise выполняется в следующей итерации, так устроен event-loop. Всегда нужно ждать вылолнения промиса. Обязательно посмотри видео #1, видео #2 на эту тему
Promise:
fetch('/foo', {
credentials: 'same-origin',
method: 'GET'
}).then((response) => {
// ждем тут
сonsole.log(1);
return response.json();
}).then((data) => {
// ждем тут
сonsole.log(2);
}).then(() => {
// ждем тут
сonsole.log(3);
});
async/await
async function getData(url) {
// ждем тут
const response = await fetch(url, {
credentials: 'same-origin',
method: 'GET'
});
сonsole.log(1);
return response.json();
}
// асинхронные функции всегда возвращают промис
// мы должны его тоже ждать как и в примере выше
getData('/foo').then((data) => {
// ждем тут
сonsole.log(2);
}).then(() => {
// ждем тут
сonsole.log(3);
});
или
async function getData(url) {
// ждем тут
const response = await fetch(url, {
credentials: 'same-origin',
method: 'GET'
});
сonsole.log(1);
// ждем тут
const data = await response.json();
сonsole.log(2);
}
// асинхронные функции всегда возвращают промис
getData('/foo').then((data) => {
// ждем тут
сonsole.log(3);
})