0

this is my first time to develop a react application.

This is my current code for calling the API call. But once this method is called, the api calls it in parallel. I want it to call it by sequence and once it fails, it will stop. How to apply promise.resolve on this method?

Thank you very much

  const doReprocess = (txnSeqs = []) => {

    txnSeqs.forEach(async txnSeq => {
      setIsReprocessing(txnSeq, ReprocessStatus.RUNNING);
      try {
        const result = await axios.post(apiBaseUrl + txnSeq, {}, {
          headers: {
            'Content-Type': 'application/json'
          }
        });
        setIsReprocessing(txnSeq, ReprocessStatus.SUCCESS, result);
      } catch (err) {
        setIsReprocessing(txnSeq, ReprocessStatus.ERROR, err.response.data || err);
      }
    });
  }


Dan
  • 559
  • 4
  • 9
  • 23
  • 3
    Use a `for (const txnSeq of txnSeqs) {` loop instead of a `forEach` call. That’s it. – Ry- Jun 21 '19 at 06:11
  • 2
    Since you can apparently use `async`/`await`, you have no need of the Promise `reduce` trick. Note that to use the [linked question's answers](https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop), you'll need to make `doReprocess` an `async` function, which means it will return a promise that the caller will need to consume. (But you'd need to return a promise with the reduce trick too.) – T.J. Crowder Jun 21 '19 at 06:16
  • Hi Ry, when I edited the for Each loop call into for, there was an error: Parsing error: Can not use keyword 'await' outside an async function – Dan Jun 21 '19 at 06:42
  • 1
    @Dan As TJ just said, you need to make `doReprocess` an `async` function – Bergi Jun 21 '19 at 06:50
  • Hi, I already got it to work, but when there is an error, the api post call still proceeds – Dan Jun 21 '19 at 07:18

0 Answers0