Jaume Mal
Jaume Mal

Reputation: 658

Fetch within promise, sporadical reversed chain order

I am chaining two calls to a function that uses fetch and returns a promise.

The calls sometimes arrive in the wrong order, reversed.

I assume my function code is wrong, derived from a bad understanding of either promises, fetch, or both.

This is the function code, simplified:

function shop(id) {
  return new Promise(function(resolve, reject) {
    fetch('/shop', {
      method: 'post',
      body: JSON.stringify({id: id}) ,
      headers: {'Content-type': 'application/json '}
      }).then(function (response) {
        return response.json();
      }).then(function (data) {
        console.log(data);
        resolve(data);
      })
  })
}

I chain the function in this manner:

shop('potatoe')
.then(shop('mushrooms'));

As explained, these two sometimes arrive in the wrong order, with mushrooms being shopped before potatoes.

May I have my returns or resolve() wrongly written in the shop() function?

Thank you for your help.

Upvotes: 1

Views: 56

Answers (1)

trincot
trincot

Reputation: 350232

The main issue is that you call shop('mushrooms') immediately, synchronously. You didn't pass a callback to the then method, but instead executed what would be the intended callback. So change the main code to:

shop('potatoe')
.then(() => shop('mushrooms'));

This solves your problem.

However, you are creating a useless promise in your function. The fetch().then().then() chain already returns a promise; you don't need to create yet another one. Read about the promise constructor antipattern.

So remove this new Promise wrapper, and remove the final .then() call which was only there to call resolve:

function shop(id) {
    // return the promise returned by this promise chain:
    return fetch('/shop', {
        method: 'post',
        body: JSON.stringify({id: id}) ,
        headers: {'Content-type': 'application/json '}
    }).then(function (response) {
        return response.json();
    });
}

Upvotes: 1

Related Questions