0

I am trying to update multiple items at once, and I have to make a network request for each item. I am using fetch for making the request.

Here's an example of what I mean:

const updateItems = items => items.forEach(item => api.create(item))

api.create might look something like this:

create: item => fetch(url, config(item)).then(handleErr).then(handleRes)

How can I make ensure that I am batching all things successfully? Each create is a promise, but I am having trouble using Promise.all as a wrapper because I get the following error: Cannot read property 'Symbol(Symbol.iterator)' of undefined

However, the updates are successful, so I'm doing something wrong!

a person
  • 1,518
  • 3
  • 17
  • 26

1 Answers1

1

Your code should be: fetch(url, config(item)).then(handleRes).catch(handleErr) And the code calling your method should use Promise.all with items.map so the calling code can do something with the result (failed and succeeded).

An example of that (here updateItems will not catch any errors, the calling code will):

const Fail = function(details){this.details=details;},
isFail = item => (item && item.constructor)===Fail;
Promise.all(
  items.map(//map array of items to array of promises that don't reject
    item =>
      updateItems(item)
      .then(
        undefined,//do not handle resolve yet
        //when you handle the reject this ".then" will return
        //  a promise that RESOLVES to the value returned below (new Fail([item,err]))
        err=>new Fail([item,err])
      )
  )
)
.then(
  responses => {
    console.log("failed requests:");
    console.log(
      responses.filter(//only Fail type
        isFail
      )
    );
    console.log("resolved requests:");
    console.log(
      responses.filter(//anything not Fail type
        response=>!isFail(response)
      )
    );
  }
);

That code comes from the following answer explaining promises.

HMR
  • 37,593
  • 24
  • 91
  • 160