@dc65k

Как правильно сделать зависящие друг от друга сетевые запросы с помощью Promise.allSettled?

Все привет.
Есть пример сетевых запросов.
Логика следующая, например, в запросе getUser ожидается ответ от запроса getAuth.
Пример реализации:
const getAuth = () => fetch('https://jsonplaceholder.typicode.com/users/1');

const getUser = (t) => fetch(`https://jsonplaceholder.typicode.com/users/${t}`);

function getOrder(t, id) {
    // return fetch(`https://jsonplaceholder.typicode.com/${t}/${id}`);
    return fetch(`https://jsonplaceholder.typicode.com/FAILED/${id}`);
}

const request = async () => {

    let res = {};

    try {
        const response = await getAuth();
        const auth = await response.json();
        console.log('auth', auth);

        res.auth = auth.id;

    } catch (e) {
        console.log(e);
    }

    try {
        const response = await getUser(res.auth);
        const user = await response.json();
        console.log('user', user);

        res.user = user;

    } catch (e) {
        console.log(e);
    }

    try {
        const response = await getOrder('users', res.auth);
        const order = await response.json();
        console.log('order', order);

        res.order = order;

    } catch (e) {
        console.log(e);
    }

    return res;
}

request().then((result) => {
    console.log('result', result);
});


Подскажите, пожалуйста, возможна ли реализация данной логики с помощью Promise.allSettled?
Promise.allSettled([getAuth(), getUser()])
    .then(results => {
        console.log(results);

        results.forEach((result, num) => {
            if (result.status === "fulfilled") {
                console.log(result.value.body);
                console.log(result.value.status);
            }
            if (result.status === "rejected") {
                console.log(result.reason);
            }
        });
    });
  • Вопрос задан
  • 61 просмотр
Решения вопроса 1
sergiks
@sergiks Куратор тега JavaScript
♬♬
Просто склейте их в одну цепочку. Что-то типа:
макароны
const state = {};
const getJSON = response => response.json();
getAuth()
  .then(getJSON)
  .then(({ id }) => {
    state.id = id;
    return getUser(id);
  })
  .then(getJSON)
  .then(user => {
    state.user = user;
  })
  .then(() => getOrder('users', state.id))
  .then(getJSON)
  .then(({ order }) => state.order = order)
  .catch(console.error)
  .finally(() => console.log("all done", state));


возможна ли реализация данной логики с помощью Promise.allSettled?

Нет. allSettled() параллелит выполнение всех промисов и дожидается, чтобы «все расселись» – будь то resolve или reject.

Хотя, пожалуй, тут можно последние два запроса запараллелить. Они оба нуждаются сначала в авторизации, а затем могут идти независимо-одновременно.
const state = {};

// подготовка
const getJSON = response => response.json();
const getUser = id =>
  fetchUser(id)
    .then(getJSON)
    .then(({ user }) => (state.user = user));
const getOrder = id =>
  fetchOrder('users', id)
    .then(getJSON)
    .then(({ order }) => (state.order = order));

// поехали
getAuth()
  .then(getJSON)
  .then(({ id }) => {
    state.id = id;
    return Promise.allSettled([getUser(id), getOrder(id)]);
  })
  .catch(console.error)
  .finally(() => console.log('all done', state));
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы