@andrey_chirkin

Как обеспечить последовательное выполнение fetch запросов промисами?

Я хочу последовательно сделать запросы на сервер. С помощью async/await я разобрался, как сделать. С промисами последовательное выполнение не получается. В консоль выводится вначале результат post запроса, затем get запроса и в конце put.

new Promise(resolve => {
    fetch('http://localhost:5000/api/get?fname=Andrey&sname=Chirkin')
        .then(response => response.json())
        .then(data => console.log('Get query:', data))
    resolve('Done')
}) .then(fetch('http://localhost:5000/api/post', {
    method: 'Post',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        fname: 'Filip',
        sname: 'Ivanov',
        age: 24,
        birthdate: '27.07.1997'
    })
})
    .then(response => response.json())
    .then(result => console.log('Post query:', result)))

.then(fetch('http://localhost:5000/api/put', {
    method: 'PUT',
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    },
    body: JSON.stringify({
        id: 1,
        sname: 'Chirkin'
    })
})
    .then(response => response.json())
    .then(result => console.log('Put query:', result)))
  • Вопрос задан
  • 245 просмотров
Решения вопроса 1
lssssssssssl
@lssssssssssl
fetch('https://jsonplaceholder.typicode.com/todos/4')
      .then((response) => {
        response.json().then(console.log);
        return fetch('https://jsonplaceholder.typicode.com/todos/5')
      })
      .then((response) => {
        response.json().then(console.log);
        return fetch('https://jsonplaceholder.typicode.com/todos/6')
      })
      .then(response => response.json().then(console.log))
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
https://pouchdb.com/2015/05/18/we-have-a-problem-w...
Зачем new Promise? fetch сам по себе промис
посмотрите коментарий от lssssssssssl добавьте .then с выдачей результатов по вкусу
https://jsfiddle.net/y9vmhg46/1/
Ответ написан
Комментировать
Ваш ответ на вопрос

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

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