简体   繁体   中英

Break out of for loop of Promises

I come to you with a question related to for loops and promises.

So to explain the situation: I have a for loop that will run a number of times. This loop uses fetch to post to an API. Depending on what comes back as a response from each POST request, I want to break the loop if a certain condition is met.

So for example, if the loop is set to run 5 times but on the 3rd iteration the break condition is met, I do not want to execute the rest of it, therefore preventing the other POST requests from executing.

I think you will understand the issue once you see the code:

send: function () {
    const procedure = 'someProcedure';
    const fields = document.querySelectorAll('.field');
    for(let i = 0; i < fields.length; i++) {
        const obj = {
            procedure: procedure,
            saunaScheduleId: fields[i].dataset.id,
            guestMediumHID: '',
            guestMediumNumber: fields[i].innerHTML
        };
        fetch(EventBooking.variables.api, {
            method: "POST",
            mode: 'cors',
            redirect: 'follow',
            headers: new Headers({ 'Content-Type': 'application/json; charset=utf-8' }),
            body: JSON.stringify(obj)
        })
        .then(response => response.json())
        .then(data => {
            if (data[0].resultCode == 3) {
                console.log(obj.guestMediumNumber + ' booked this event.');
                return;
            }
            else if(data[0].resultCode == 0 && i == fields.length - 1) {
                console.log('Booking completed successfully!');
                EventBooking.booking.clear();
            }
        });
    }
}

From what I read, It has to do with the for loop somehow being done way ahead of the API calls. The second if in the loop seems to be doing good once all the calls have been executed successfully it shows one message for all of them.

How would you go about handling this kind of situation?

Thank you for your help. Cheers!

Use recursive

send: function () {
    const procedure = 'someProcedure';
    const fields = document.querySelectorAll('.field');
    const fetching = index => {
        if (index >= fields.length) return;
        const obj = {
            procedure: procedure,
            saunaScheduleId: fields[index].dataset.id,
            guestMediumHID: '',
            guestMediumNumber: fields[index].innerHTML
        };
        fetch(EventBooking.variables.api, {
            method: "POST",
            mode: 'cors',
            redirect: 'follow',
            headers: new Headers({ 'Content-Type': 'application/json; charset=utf-8' }),
            body: JSON.stringify(obj)
        })
        .then(response => response.json())
        .then(data => {
            if (data[0].resultCode == 3) {
                console.log(obj.guestMediumNumber + ' booked this event.');
                return;
            }
            else if(data[0].resultCode == 0 && index == fields.length - 1) {
                console.log('Booking completed successfully!');
                EventBooking.booking.clear();
            }
            fetching(index + 1);
        });
    };
    fetching(0);
}

I have decided to go for this:

Seems clean and works.

send: async function () {
        const procedure = 'SaveSaunaEventBooking';
        const fields = document.querySelectorAll('.field');
        for(let i = 0; i < fields.length; i++) {
            const obj = {
                procedure: procedure,
                saunaScheduleId: fields[i].dataset.id,
                guestMediumHID: '',
                guestMediumNumber: fields[i].innerHTML
            };
            let response = await fetch(EventBooking.variables.api, {
                method: "POST",
                mode: 'cors',
                redirect: 'follow',
                headers: new Headers({ 'Content-Type': 'application/json; charset=utf-8' }),
                body: JSON.stringify(obj)
            })
            let data = await response.json();
            if (data[0].resultCode == 3) {
                console.log(obj.guestMediumNumber + ' booked this event.');
                return;
            }
            else if (data[0].resultCode == 0 && i == fields.length - 1) {
                console.log('Booking completed successfully!');
                EventBooking.booking.clear();
            }

        }

Thanks for all your ideas and help: :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM