0

I am trying to execute three fetch requests one by one. Each fetch request should trigger on completion of previous fetch request. Below is my code

const chopSegment = (token, frame_tag_url, tag_to_delete_id, chopped_tag_array, tags_for_index_update) => (dispatch) =>  {
    let req = fetch(frame_tag_url + tag_to_delete_id + "/",
        {
            method: "DELETE",
            headers: {
                "Authorization": "Token " + token,
                "content-type": "application/json"
            }
        })
    req.then(response => {
        if (!response.ok) {
            throw response;
        }
        else
            return response.json();
    }).then(response => {
        return fetch(frame_tag_url,
            {
                method: "POST",
                headers: {
                    "Authorization": "Token " + token,
                    "content-type": "application/json",
                },
                body : JSON.stringify(tags_for_index_update)
            }).then(response1 => {
            if (!response1.ok) {
                throw response1;
            }
            return response1.json();
        }).then(response => {
            for(let i = 0; i < chopped_tag_array.length; i++){
                return  fetch(frame_tag_url,
                    {
                        method: "POST",
                        body: JSON.stringify(chopped_tag_array[i]),
                        headers: {
                            "Authorization": "Token " + token,
                            "content-type": "application/json"
                        }
                    })
                .then(response2 => {
                    if (!response2.ok) {
                        throw response2;
                    }
                    return response2.json();
                }).then(response2 => {
                    dispatch(chopSegmentSuccess(response2))
                }).catch(error => {

                })
            }
        }).catch(error => {

        })
    }).catch(error => {
    })
}

In my code, only first fetch i.e. "DELETE" gets executed? What am I doing wrong?

EdG
  • 1,947
  • 5
  • 34
  • 74
  • One thing that immediately stands out is that you are catching errors, but then proceed to ignore them. The point of `catch()` is to handle errors. – Evert May 19 '20 at 22:48
  • I would suggest to remove the return from fetch keyword and try again. – chandan_kr_jha May 19 '20 at 22:50

2 Answers2

0

You can't do fetches in a loop. You're returning the first fetch that completes. Use promises or await/async to fetch in a loop. How to return many Promises in a loop and wait for them all to do other stuff

elisecode247
  • 106
  • 6
-1

I'd rather do it this way, Create an IIFE and call it recursively for the subsequent fetch request:

return dispatch =>{
    var ctr = 0;
    (function myFunc(url, headerObj){
        fetch(url, headerObj)
        .then(response => {
            response.json().then(data=>{
                ctr++;
                if(ctr ===1 ){ // This could be any condition, say, something on the basis of response; I have taken `ctr` as a condition
                    myFunc(url, { //You may change this even to different URL, if needed
                        method: 'POST',
                        headers: {
                            'content-type': 'application/json', 
                             'body': ...,
                             'Authorization':...

                          }
                    });
                }else if(ctr === 2){
                    myFunc(url, {
                        method: 'POST',
                        headers: {
                            'content-type': 'application/json', 
                             'body': ...,
                             'Authorization':...
                          }
                    });
                }else{
                   // Any other code
                }

            })
        })
    })(url, headerObj);
}
SE_net4 the downvoter
  • 21,043
  • 11
  • 69
  • 107
ABGR
  • 3,606
  • 1
  • 15
  • 35